ruby - Prevent this variable from changing -


i doing word problem. trying set 2 arrays. 1 serves benchmark (doesn't change during iteration), other changes during iteration. here example:

seed = 1 = [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1]] bm = a[seed] a[seed].each.with_index |x, i|   if bm.include?(0)     a[seed][i] = "wrong"   else     a[seed][i] = 0 unless == 3   end end  #         => [[1, 1, 1, 1], [0, "wrong", "wrong, "wrong"], [1, 1]] # should => [[1, 1, 1, 1], [0, 0, 0, 1], [1, 1]] bm #        => [0, "wrong", "wrong, "wrong"] # should => [1, 1, 1, 1] 

usually if want have "before , after" in code can do:

a = 5 b = a = 6 # => 6 b # => 5 

in case, doesn't change b when a changed. why happen? suspect it's because second example storing number b whereas in first example, it's storing code only. can fix this? bad practice?

you're right. when assign array bm you're assigning reference (or pointer, not sure ruby prefers call it) a[seed]. can see printing out object_id of both variables:

> a[seed].object_id => 70347648205960 > bm.object_id => 70347648205960 

note pointing same internal object. solution use dup duplicate array , assign new 1 bm2.

> bm2 = a[seed].dup => [1, 1, 1, 1] > bm2.object_id => 70347649948520 

note object_id has changed. , if make change...

> a[seed][0] = 'wrong' => "wrong" > a[seed] => ["wrong", 1, 1, 1] > bm => ["wrong", 1, 1, 1] > bm2 => [1, 1, 1, 1] 

you might want google read object_id, dup, , clone similar dup, has differences.


Comments