简体   繁体   中英

Ruby: How to copy the multidimensional array in new array?

seating_arrangement [ [:first, :second, :none], [:first, :none, :second], [:second, :second, :first], ]

I need to copy this array into new array. I tried to do it by following code:

class Simulator
 @@current_state

def initialize(seating_arrangement)
  @@current_state = seating_arrangement.dup
end

But whenever I am making any changes to seating_arrangement current_state changes automatically. I wanted to keep current_state separately. I am newbie in ruby . Please help me here

def initialize(seating_arrangement)
  @@current_state = seating_arrangement.map(&:dup)
end

dup does not create a deep copy, it copies only the outermost object. From that docs:

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj.

If you are not sure how deep your object might be nested then the easiest way to create deep copy might be to serialize and de-serialize the object:

@@current_state = Marshal.load(Marshal.dump(seating_arrangement))

If you use Rails 4.x or above, just use:

 array.deep_dup

See doc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM