Sitemap
Ewa Barczykowska

Ewa Barczykowska

Hey, I'm Ewa(pronounced: Eh-vah), I'm a DevOps engineer at a large telecom company.

Press enter or click to view image in full size
Indian sweets.

Member-only story

#clone and #dup in Ruby

5 min readOct 30, 2023

--

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.dup

Now 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?

  1. array will stay intact, duplicated_array will have all its elements upcased
  2. both array and duplicated_array will 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…

--

--

Ewa Barczykowska
Ewa Barczykowska

Written by Ewa Barczykowska

Hey, I'm Ewa(pronounced: Eh-vah), I'm a DevOps engineer at a large telecom company.