How can I prepend to an array in Ruby?

arrays, ruby

Solution

array = ['b', 'c']

array.unshift('a')

p array
=> ['a', 'b', 'c']

As Scott G has pointed out in the comments, as of Ruby 2.5.0 `#prepend` has been added as an alias for `#unshift`.

Problem

What is the best way to prepend to an array in Ruby. Perhaps something similar to Python's `list.insert(0, 'foo')`? I'd like to be able to add an element to a Ruby array at the 0 position and have all other elements shifted along.

Original source

Related problems