How to Add a Value to the Front and Return a New Array in Ruby?

In Ruby, to add a value to the front and return a new array (as opposed to modifying it in-place), you can do the following:

existing_arr = ["bar", "baz"]
new_arr = ["foo", *existing_arr]

print new_arr # ["foo", "bar", "baz"]

In the example above, the value you wish to add to the front goes at the first index in the new array and the existing array is unpacked (using *) right after. This does not mutate/modify the original array. Another way to achieve the same is by using the + operator, for example, like so:

existing_arr = ["bar", "baz"]
new_arr = ["foo"] + existing_arr

print new_arr # ["foo", "bar", "baz"]

This would return a new array with the value 'foo' at the front, followed by all elements of "existing_arr".


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.