Jeremy Smith Jeremy Smith - 6 months ago 13
Ruby Question

What is the easiest way to push an element to the beginning of the array?

I can't think of of a one line way to do this. Is there a way?

Answer

What about using the unshift method?

ary.unshift(obj, ...) → ary
Prepends objects to the front of self, moving other elements upwards.

And in use:

irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"