Frantisek ZACEK
8/17/2008 2:21:00 PM
On Sun, Aug 17, 2008 at 3:55 PM, Marcio Braga <mbraga0001@gmail.com> 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