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