What is the difference of Ruby's Array#to_a method -
for example:
a = [1,2,3,4] b = c = a.to_a a.insert(0,0) #=> [0,1,2,3,4] b #=> [0,1,2,3,4] c #=> [0,1,2,3,4]
why output of array b
, c
same? if want copy of array a
, not reference one, method should use?
you can
b = a.dup
old post
can try if there no easier way
b = a.map {|x| x}
it works
1.9.3-p448 :001 > = [1,2,3] => [1, 2, 3] 1.9.3-p448 :002 > b = => [1, 2, 3] 1.9.3-p448 :003 > c = a.map{|x| x} => [1, 2, 3] 1.9.3-p448 :004 > a<<0 => [1, 2, 3, 0] 1.9.3-p448 :005 > b => [1, 2, 3, 0] 1.9.3-p448 :006 > c => [1, 2, 3]
but shallow copy though.
according this post, a.dup
easier way.
Comments
Post a Comment