What is the easiest way to push an element to the beginning of the array?
ArraysRubyArrays Problem Overview
I can't think of a one line way to do this. Is there a way?
Arrays Solutions
Solution 1 - Arrays
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]"
Solution 2 - Arrays
You can use insert
:
a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]
Where the first argument is the index to insert at and the second is the value.
Solution 3 - Arrays
array = ["foo"]
array.unshift "bar"
array
=> ["bar", "foo"]
be warned, it's destructive!
Solution 4 - Arrays
Since Ruby 2.5.0, Array ships with the prepend
method (which is just an alias for the unshift
method).
Solution 5 - Arrays
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.
Solution 6 - Arrays
You can use methodsolver
to find Ruby functions.
Here is a small script,
require 'methodsolver'
solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }
Running this prints
Found 1 methods
- Array#unshift
You can install methodsolver using
gem install methodsolver
Solution 7 - Arrays
You can use a combination of prepend
and delete
, which are both idiomatic and intention revealing:
array.delete(value) # Remove the value from the array
array.prepend(value) # Add the value to the beginning of the array
Or in a single line:
array.prepend(array.delete(value))