配列の参照・代入
Rubyでは、配列の参照はというメソッド、代入は=というメソッドになります。
class RubycoArray
def initialize(size)
@arr = []
@size = size
end
def []=(index, value)
if index < 0 or @size <= index
raise "index is out of bounds"
else
@arr[index] = value
end
end
def [](index)
if index < 0 or @size <= index
raise "index is out of bounds"
else
return @arr[index]
end
end
end
a = RubycoArray.new(3)
a[0] = 0
a[1] = 100
a[2] = 200
# a[3] = 300 # in `[]=': index is out of bounds (RuntimeError)
p a # => #<RubycoArray:0x29466e8 @size=3, @arr=[0, 100, 200]>
p a[0] # => 0
p a[1] # => 100
p a[2] # => 200
# p a[3] # => in `[]': index is out of bounds (RuntimeError)