How to Prepend a Value to a Ruby Array?

Find out how you can prepend a value to an array in Ruby

In Ruby, you can prepend a value to an existing array by using the Array#unshift method, for example, like so:

a = ["bar", "baz"]
a.unshift("foo")

print a #=> ["foo", "bar", "baz"]

Starting with Ruby 2.5+, you may also use the Array#prepend method, which is an alias for Array#unshift.

As an alternative, you may use the Array#insert method to add a value to the start of an array, for example, like so:

a = ["bar", "baz"]
a.insert(0, "foo")

print a #=> ["foo", "bar", "baz"]

Using any of these methods would do in-place modification of the array (as opposed to returning a new one) — which means that it would mutate/modify the original array.


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