How to Append a Value to a Ruby Array?

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

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

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

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

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

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

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.