Member-only story
#clone and #dup in Ruby
If you think that the #clone and #dup method work in mysterious ways — you are in the right place, together we’ll reveal the mystery!
Let’s get right to the point. I want to duplicate an array. The array I have is:
array = ["a", "b", "c"]I will use the dupmethod to create a duplicate of the above array:
duplicated_array = array.dupNow when I print both the original and the duplicate, I see 2 arrays that are same:
p array
#=>["a", "b", "c"]
p duplicated_array
#=>["a", "b", "c"]Nothing surprising there. Now I decide to mutate the elements of the duplicated_array:
duplicated_array.map { |e| e.upcase! }What do you think will happen now?
arraywill stay intact,duplicated_arraywill have all its elements upcased- both
arrayandduplicated_arraywill have all their elements upcased
Take your guess. You have 50% chance of being right! Or better, try it in irb. Scroll down to find out the correct answer.
Well…
p array
#=> ["A", "B", "C"]
p duplicated_array
#=> ["A", "B", "C"]What?! What is happening here? What is happening is that when we use #dup…






