From: Frantisek ZACEK Date: 2008-08-17T23:20:53+09:00 Subject: Re: Matrix: Need help to understand this behavior On Sun, Aug 17, 2008 at 3:55 PM, Marcio Braga wrote: > a=[1] > b=a # make matrix "b" equal matrix "a", but expected 2 > separated matrices > b[0]=2*b[0] # I want to change matrix "b" (and not matrix "a") > p a # print matrix "a" and see the "issue" > > The expected value in the matrix "a" should be 1, but instead it is 2. > > Why ? > > Thank you. > Marcio Typical Ruby behavior. In Ruby, variables reference objects rather than contain values. Therefore, when you write b = a, b references the same object as a does. Therefore, when you modify b, you modify a. See the obejct_ids in your code: $>cat mat.rb #!/usr/bin/env ruby -wKU a = [1] b = a puts a.object_id puts b.object_id b[0] = 2 * b[0] p a p b $>ruby mat.rb 284610 284610 [2] [2] $> See ? same objects. To do what you want, you need to duplicate your array rather than just assign it : $>cat dup_mat.rb #!/usr/bin/env ruby -wKU a = [1] b = a.dup puts a.object_id puts b.object_id b[0] = 2 * b[0] p a p b $>ruby dup_mat.rb 284540 284530 [1] [2] $> Hope it helped. -- Frantisek ZACEK (zacek_f) -- SRS 2008