ChatGPT解决这个技术问题 Extra ChatGPT

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

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


m
mu is too short

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]"

I looked, just didn't see them in a quick scan.
@Ed: The method list at the top of the page could be better formatted, it is very difficult to visually scan as it is. I found it because I knew the method name I was looking for :)
If you are having trouble remembering between shift and unshift as to which adds to the array and which removes from the array, drop an 'f' from the names mentally and you get an all-too-clear picture as to the direction. (And then you have to remember that these methods don't work on the "end" of the array. ;)
@Phrogz The best mnemonic technique I've heard in years! :-)
@Phrogz I am still using that mnemonic to this day, and feeling weird passing it on to other people.
D
DaveMongoose

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.


J
John H
array = ["foo"]
array.unshift "bar"
array
=> ["bar", "foo"]

be warned, it's destructive!


s
steenslag

Since Ruby 2.5.0, Array ships with the prepend method (which is just an alias for the unshift method).


This also works with ruby 2.4.4p296, so maybe just with ruby 2.4?
m
ma11hew28

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.


a
akuhn

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

Cool, didn't think this would be possible to write LOL
irb> require 'methodsolver' causes LoadError: cannot load such file -- method_source from ... from /var/lib/gems/1.9.1/gems/methodsolver-0.0.4/lib/methodsolver.rb:2. Ruby 1.9.3p484, irb 0.9.6, Ubuntu 14.
Try using pry instead of irb
W
Wilson Silva

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