From: Jano Svitok Date: 2008-01-09T23:48:51+09:00 Subject: Re: Why this behaviour? On Jan 9, 2008 3:35 PM, Daniele Antani wrote: > Hello to all, > > i can't understand the follow behaviour: > > class Player > attr_accessor :hand > def initialize(hand) This copies reference to the array, use #dup to create a copy (note that it's not recursive): - @hand = hand + @hand = hand.dup > end > end > > def roba(player) > p2 = Player.new(player.hand) > change p2 > print "p2 = " > p p2 > print "player = " > p player > end > > def change(player) > player.hand.push(3) > end > > > p1 = Player.new([2, 3, 4]) > roba p1 > > __END__ > > output is: > p2 = # > player = # > > > Why the change affects both objects? I want to copy the first object and > work on the copy without affecting the original. > > Thanks > -- > Posted via http://www.ruby-forum.com/. > >