Pon el índice primero con each_with_index
Frecuentes
Visto 356 equipos
2
Estoy usando Array() con each_with_index para generar una matriz con índice, pero quiero que genere
[[0,obj1],[1,obj2]....]
mientras que each_with_index hace que salga
[[obj1,0],[obj2,1]....]
¿Hay alguna forma de que esto se pueda arreglar fácilmente?
Como se le ha pedido que muestre el código.
Array(test.each_with_index)
2 Respuestas
3
Intenta agregar .map { |x| x.reverse }
después de la each_with_index
.
Respondido el 12 de junio de 12 a las 18:06
Gracias, sin embargo, todo lo que hace es devolver los objetos invertidos. irb(main):001:0> test=["poppy","kitty","puppy"] => ["poppy", "kitty", "puppy"] irb(main):002:0> Array(test.each_with_index.map{|x| x.reverse}) => ["yppop", "yttik", "yppup"]
- katgaea
Debe ejecutar esto en la matriz: ["foo", "bar"].each_with_index.to_a.map {|x| x.reverse } => [[0, "foo"], [1, "bar"]]
. - Lars Kothoff
Gracias, eso es exactamente lo que necesitaba - katgaea
Funciona aqui: Array(%w(a b c).each_with_index.map &:reverse).inspect
devoluciones [[0, "a"], [1, "b"], [2, "c"]]
. - mateo moreira
@MatheusMoreira ¿Puedo preguntar qué lo hace mejor? - katgaea
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas ruby or haz tu propia pregunta.
@Sergio prácticamente dije lo que estaba haciendo, era ruby básico de Array (array.each_with_index) - KatGaea