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

Append a value to a Ruby array in an immutable way

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.


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