How to make a copy of an array and manipulate its element in ruby -
i have array copy , change element's value. how can (ruby 1.9.3p429)
a = array.new(2,"test") #a => ["test","test"] #a.object_id => 21519600 #a[0].object_id => 21519612 b = a.clone #b => ["test","test"] #b.object_id => 22940520 #b[0].object_id => 21519612 c = a.dup #c => ["test","test"] #c.object_id => 22865176 #c[0].object_id => 21519612 d = array.new(a) #d => ["test","test"] #c.object_id => 23179224 #d[0].object_id => 21519612 c[0].upcase! #produces #a => ["test","test"], #b => ["test","test"], #c => ["test","test"] ...`
in ruby every object reference object if have array
x = [a, b, c, d]
and copy array
y = x.clone
it copy references original objects, not objects themselves.
to want have copy objects in loop, you're focused on how want achieve array copying, instead of achieving ultimate goal, new array consists of upcased items of original array.
explore enumerable module , find things #map
, #select
, #inject
, etc. instance how copy of array names upcased:
["test", "test"].map { |element| element.upcase }
Comments
Post a Comment