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.
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
Ruby has Array#unshift to prepend an element to the start of an array and Array#push to append an element to the end of an array. The names of these methods are not very intuitive. Active Support from Rails already has aliases for the unshift and push methods , namely prepend and append.
Inserts an array element at the beginning of an array and shifts the positions of the existing elements to make room.
array = ['b', 'c'] array.unshift('a') p array => ['a', 'b', 'c']
Another way than Steve's answer
array = ['b', 'c'] array = ['a'] + array #["a", "b", "c"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With