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

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

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

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

In the example above, the existing array is unpacked first (using *), and the value you wish to add to the end is added 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 = ["foo", "bar"]
new_arr = existing_arr + ["baz"]

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

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


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.