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