From: Mason Kelsey Date: 2009-09-10T23:43:34+09:00 Subject: Re: How Are Variables Kept Independent of Each Other Yet Pas --0016e64bd3e637765304733a39d7 Content-Type: text/plain; charset=ISO-8859-1 By the way, I just modified and tested my code with your solution: new_state = [] current_state.each do |substate| new_state << substate.dup end and it worked beautifully! If others are following this conversation, the "new_state = []" is needed if the variable, new_state, has not been defined at a prior time. Ruby authors need to add the dup method in an early chapter where they cover assignments! Not included in "Beginning Ruby" 2nd ed. The pickaxe book, "Programming Ruby 1.9", only mentions dup (and clone) in chapter 27 on built-in classes and methods without any code examples. "Ruby Cookbook" doesn't mention it at all. "Ruby in a Nutshell" only says on page 48 "o.dup Creates a copy of the object (copying the content)." Again, much thanks, No Sam On Thu, Sep 10, 2009 at 12:44 AM, 7stud -- wrote: > Yossef Mendelssohn wrote: > > > > Mason, you're going to want to make an actual copy of the original > > variable, not simply a new pointer to it (which is what you get when > > you do something like `b = a`). In many cases, calling .dup or .clone > > will work. (As in `b = a.dup` or `b = a.clone`.) > > > > However, since you have an array of arrays, you're going to need a > > "deep copy". I believe `b = Marshal.load(Marshal.dump(a))` is the > > standard idiom. > > Or, if that offends your sensibilities, in your case you can do this: > > arr = [ > [1, 2], > ["a", "b"] > ] > > > arr_copy = [] > > arr.each do |subarr| > arr_copy << subarr.dup > end > > p arr > p arr_copy > > --output:-- > [[1, 2], ["a", "b"]] > [[1, 2], ["a", "b"]] > > > arr[0][1] = "******" > > p arr > p arr_copy > > --output:-- > [[1, "******"], ["a", "b"]] > [[1, 2], ["a", "b"]] > > -- > Posted via http://www.ruby-forum.com/. > > --0016e64bd3e637765304733a39d7--