Lets say I create an object with an array. I then create another object that takes said array and modifies it within its own scope. If I try to access original array from the first object again, shouldn't I have the unmodified version of the array?
Example code:
class Test
attr_accessor :g
def initialize
@g = [1,2,3]
end
def do_stuff
Test_Two.new(@g).modify
end
end
class Test_Two
def initialize(h)
@h = h
end
def modify
@h[0] +=1
end
end
t = Test.new
puts "#{t.g}"
t.do_stuff #this shouldn't modify t.g
puts "#{t.g}"
Expected output:
[1,2,3]
[1,2,3]
Actual output:
[1,2,3]
[2,2,3]
Weirdly enough, if I make g an integer, I get what I expect:
class Test
attr_accessor :g
def initialize
@g = 1
end
def do_stuff
Test_Two.new(@g).modify
end
end
class Test_Two
def initialize(h)
@h = h
end
def modify
@h +=1
end
end
t = Test.new
puts "#{t.g}"
t.do_stuff #this shouldn't modify t.g
puts "#{t.g}"
Output:
1
1
Aucun commentaire:
Enregistrer un commentaire