From: Ralph Shnelvar Date: 2009-11-14T21:20:00+09:00 Subject: Re: how to copy array in ruby l> Array#dup creates a copy of the array, not of the elements in the l> array, aka a shallow copy. Is there a way to make a deep copy? That is ... in the code below, could b.dup be replaced with something like b.deepdup? irb(main):019:0> a1 = [1,2,3,4] => [1, 2, 3, 4] irb(main):020:0> b = [a1,5] => [[1, 2, 3, 4], 5] irb(main):021:0> c1 = b => [[1, 2, 3, 4], 5] irb(main):022:0> c2 = b.dup => [[1, 2, 3, 4], 5] irb(main):023:0> a1[0] = "hi" => "hi" irb(main):024:0> a1 => ["hi", 2, 3, 4] irb(main):025:0> c1 => [["hi", 2, 3, 4], 5] irb(main):026:0> c2 # because of the shallow copy, c2[0][0] is "hi" instead of a naively # assumed 1. => [["hi", 2, 3, 4], 5] irb(main):027:0> c1[1] = "bye" => "bye" irb(main):028:0> c1 => [["hi", 2, 3, 4], "bye"] irb(main):029:0> c2 # The shallow copy gives the expected result for c2[1], below. => [["hi", 2, 3, 4], 5]