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

Prepend a value to a Ruby array in an immutable way

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


Hope you found this post useful. It was published . Please show your love and support by sharing this post.