¿Cuál es la forma más fácil de empujar un elemento al principio de la matriz?


No puedo pensar en una forma de una línea para hacer esto. ¿Hay alguna manera?

 169
Author: Arslan Ali, 2011-05-22

6 answers

¿Qué pasa con el uso de la unshift ¿método?

ary.unshift(obj, ...) → ary
Antepone objetos al frente del yo, moviendo otros elementos hacia arriba.

Y en uso:

irb>> a = [ 0, 1, 2]
=> [0, 1, 2]
irb>> a.unshift('x')
=> ["x", 0, 1, 2]
irb>> a.inspect
=> "["x", 0, 1, 2]"
 332
Author: mu is too short,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-13 16:05:55

Puedes usar insert:

a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]

Donde el primer argumento es el índice a insertar y el segundo es el valor.

 40
Author: Ed S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-31 16:47:36
array = ["foo"]
array.unshift "bar"
array
=> ["bar", "foo"]

Tenga cuidado, es destructivo!

 18
Author: John H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-22 01:50:22

También puede usar concatenación de matrices :

a = [2, 3]
[1] + a
=> [1, 2, 3]

Esto crea un nuevo array y no modifica el original.

 9
Author: ma11hew28,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-16 17:56:08

Puedes usar methodsolver para encontrar funciones Ruby.

Aquí hay un pequeño script,

require 'methodsolver'

solve { a = [1,2,3]; a.____(0) == [0,1,2,3] }

Al ejecutar esto se imprime

Found 1 methods
- Array#unshift

Puede instalar methodsolver usando

gem install methodsolver
 6
Author: akuhn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-26 01:14:17

Desde Ruby 2.5.0, el Array se envía con el método prepend (que es solo un alias para el método unshift).

 0
Author: steenslag,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-13 19:58:50