Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prepend to an array in Ruby? [duplicate]

Tags:

arrays

ruby

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.

like image 817
nettux Avatar asked Jun 04 '14 11:06

nettux


People also ask

How do you append an array to another array in Ruby?

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

How do you append an element to an array Ruby?

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.

What is prepend array?

Inserts an array element at the beginning of an array and shifts the positions of the existing elements to make room.


2 Answers

array = ['b', 'c']  array.unshift('a')  p array => ['a', 'b', 'c'] 
like image 184
SteveTurczyn Avatar answered Oct 27 '22 17:10

SteveTurczyn


Another way than Steve's answer

array = ['b', 'c'] array = ['a'] + array #["a", "b", "c"] 
like image 23
peter Avatar answered Oct 27 '22 19:10

peter