I can't think of a one line way to do this. Is there a way?
6 Answers
407
votes
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]"
53
votes
19
votes
13
votes
You can also use array concatenation:
a = [2, 3]
[1] + a
=> [1, 2, 3]
This creates a new array and doesn't modify the original.