index array ruby arrays each

index - Ruby array accede a 2 elementos consecutivos(encadenados) a la vez



ruby select (4)

Ahora, esta es la matriz,

[1,2,3,4,5,6,7,8,9]

Quiero,

[1,2],[2,3],[3,4] upto [8,9]

Cuando lo hago, each_slice (2) me sale,

[[1,2],[3,4]..[8,9]]

Actualmente estoy haciendo esto,

arr.each_with_index do |i,j| p [i,arr[j+1]].compact #During your arr.size is a odd number, remove nil. end

¿Hay una mejor manera?


Casi lo entiendes bien :)

arr = [1,2,3,4,5,6,7,8,9] arr.each_cons(2) do |chunk| p chunk end # >> [1, 2] # >> [2, 3] # >> [3, 4] # >> [4, 5] # >> [5, 6] # >> [6, 7] # >> [7, 8] # >> [8, 9]


Ruby lee tu mente. ¿Quieres elementos ecutivos?

[1, 2, 3, 4, 5, 6, 7, 8, 9].each_cons(2).to_a # => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]


Y si quisieras implementar tus propios each_cons :

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] cons = 2 0.upto(arr.size - cons) do |i| p arr[i, cons] end

Salida:

[1, 2] [2, 3] [3, 4] [4, 5] [5, 6] [6, 7] [7, 8] [8, 9]


.each_cons hace exactamente lo que quieres.

[1] pry(main)> a = [1,2,3,4,5,6,7,8,9] => [1, 2, 3, 4, 5, 6, 7, 8, 9] [2] pry(main)> a.each_cons(2).to_a => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]