class Point
attr_accessor :x, :y
def initialize(x =0, y = 0)
@x = x
@y = y
end
def to_s
"x: #{@x}; y: #{@y}"
end
def move(x,y)
@x = @x + x
@y = @y + y
end
end
my_point= Point.new(4,6)
puts my_point
my_point.move(7,14)
puts my_point
puts
my_square = Array.new(4, Point.new)
a_square = []
my_square.each {|i| puts i}
puts
my_square.each do|i|
b = i
b.move(2,4)
a_square<< b
end
a_square.each {|i| puts i}
The result
x: 4; y: 6
x: 11; y: 20
x: 0; y: 0
x: 0; y: 0
x: 0; y: 0
x: 0; y: 0
x: 8; y: 16
x: 8; y: 16
x: 8; y: 16
x: 8; y: 16
when it should be
x: 4; y: 6
x: 11; y: 20
x: 0; y: 0
x: 0; y: 0
x: 0; y: 0
x: 0; y: 0
x:2; y: 4
x:2; y: 4
x:2; y: 4
x:2; y: 4
my_square = Array.new(4, Point.new)is the same thing aspoint = Point.new; my_square = Array.new(4, point). The array contains 4 references to the same object of typePoint.