Cómo mapear con índice en Ruby?
¿Cuál es la forma más fácil de convertir
[x1, x2, x3, ... , xN]
A
[[x1, 2], [x2, 3], [x3, 4], ... , [xN, N+1]]
10 answers
Si está utilizando ruby 1.8.7 o 1.9, puede usar el hecho de que los métodos iteradores como each_with_index
, cuando se llaman sin un bloque, devuelven un objeto Enumerator
, al que puede llamar Enumerable
métodos como map
on. Así que puedes hacer:
arr.each_with_index.map { |x,i| [x, i+2] }
En 1.8.6 puedes hacer:
require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }
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-01-15 01:47:09
Ruby tiene Enumerador#with_index(offset = 0) . Para convertir la matriz a un enumerador, use Object#to_enum o Array#map , lo que le parezca más declarativo:
[:a, :b, :c].map.with_index(2).to_a
#=> [[:a, 2], [:b, 3], [:c, 4]]
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-07-07 11:57:47
En ruby 1.9.3 hay un método encadenable llamado with_index
que se puede encadenar a map.
Por ejemplo:
array.map.with_index { |item, index| ... }
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-08-21 11:02:46
Sobre la ofuscación superior:
arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)
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-11-10 03:33:14
Aquí hay dos opciones más para 1.8.6 (o 1.9) sin usar enumerador:
# Fun with functional
arr = ('a'..'g').to_a
arr.zip( (2..(arr.length+2)).to_a )
#=> [["a", 2], ["b", 3], ["c", 4], ["d", 5], ["e", 6], ["f", 7], ["g", 8]]
# The simplest
n = 1
arr.map{ |c| [c, n+=1 ] }
#=> [["a", 2], ["b", 3], ["c", 4], ["d", 5], ["e", 6], ["f", 7], ["g", 8]]
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-01-15 02:46:59
Siempre he disfrutado de la sintaxis de este estilo:
a = [1, 2, 3, 4]
a.each_with_index.map { |el, index| el + index }
# => [1, 3, 5, 7]
Al invocar each_with_index
obtendrá un enumerador que puede mapear fácilmente con su índice disponible.
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
2015-10-28 15:47:24
a = [1, 2, 3]
p [a, (2...a.size+2).to_a].transpose
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
2013-01-05 23:17:46
module Enumerable
def map_with_index(&block)
i = 0
self.map { |val|
val = block.call(val, i)
i += 1
val
}
end
end
["foo", "bar"].map_with_index {|item, index| [item, index] } => [["foo", 0], ["bar", 1]]
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
2013-03-07 12:12:06
A menudo hago esto:
arr = ["a", "b", "c"]
(0...arr.length).map do |int|
[arr[int], int + 2]
end
#=> [["a", 2], ["b", 3], ["c", 4]]
En lugar de iterar directamente sobre los elementos de la matriz, está iterando sobre un rango de enteros y usándolos como índices para recuperar los elementos de la matriz.
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
2013-11-26 02:40:14
Una manera divertida, pero inútil de hacer esto:
az = ('a'..'z').to_a
azz = az.map{|e| [e, az.index(e)+2]}
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
2014-05-08 21:06:23