Saari Development

Ali Rizvi's Technical Blog as a Professional Software Development Engineer

Ruby : Deep Copy

with one comment

# problem
a = [[0, 1], [10], 19]
b = a.dup
b[0][1] = 100 #=> b = [[0, 100], [10], 19] and a = [[0, 100], [10], 19]

# solution
a = [[0, 1], [10], 19]
b = Marshal.load(Marshal.dump(a))
b[0][1] = 100 #=> b = [[0, 100], [10], 19] and a = [[0, 1], [10], 19]
Advertisements

Written by imsaar

January 9, 2008 at 10:13 pm

Posted in code, ruby

One Response

Subscribe to comments with RSS.

  1. hmmm. This does not work if you are trying to dump a Hash created with a custom initializer:

    irb(main):001:0> h1 = Hash.new{ |h,k| h[k] = 5 }
    => {}
    irb(main):002:0> h1[“a”]
    => 5
    irb(main):003:0> h1
    => {“a”=>5}
    irb(main):004:0> h2 = Marshal.load(Marshal.dump(h1))
    TypeError: can’t dump hash with default proc
    from (irb):4:in `dump’
    from (irb):4
    from :0
    irb(main):005:0> Marshal.dump(h1)
    TypeError: can’t dump hash with default proc
    from (irb):5:in `dump’
    from (irb):5
    from :0

    Arnab Deka

    February 20, 2009 at 12:30 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: