0

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

1
  • my_square = Array.new(4, Point.new) is the same thing as point = Point.new; my_square = Array.new(4, point). The array contains 4 references to the same object of type Point. Commented Jan 24, 2021 at 16:16

1 Answer 1

4

Array.new(4, Point.new) will create an array with the same object (in this case an instance of Point).

my_square = Array.new(4, Point.new)
p my_square.map(&:object_id).uniq.count
#=> 1

If you change to Array.new(4) { Point.new }, this will populate array with different objects.

my_square = Array.new(4) { Point.new }
p my_square.map(&:object_id).uniq.count
#=> 4

Check this for more info.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.