Ruby array reverse_each_with_index
Я хотел бы использовать что-то вроде reverse_each_with_index
для массива.
Пример:
array.reverse_each_with_index do |node,index|
puts node
puts index
end
Я вижу, что Ruby имеет each_with_index
, но похоже, что у него нет противоположности. Есть ли другой способ сделать это?
Ответы
Ответ 1
Если вам нужен реальный индекс элемента в массиве, вы можете сделать это
['Seriously', 'Chunky', 'Bacon'].to_enum.with_index.reverse_each do |word, index|
puts "index #{index}: #{word}"
end
Вывод:
index 2: Bacon
index 1: Chunky
index 0: Seriously
Вы также можете определить свой собственный метод reverse_each_with_index
class Array
def reverse_each_with_index &block
to_enum.with_index.reverse_each &block
end
end
['Seriously', 'Chunky', 'Bacon'].reverse_each_with_index do |word, index|
puts "index #{index}: #{word}"
end
Оптимизированная версия
class Array
def reverse_each_with_index &block
(0...length).reverse_each do |i|
block.call self[i], i
end
end
end
Ответ 2
Сначала reverse
массив, а затем используйте each_with_index
:
array.reverse.each_with_index do |element, index|
# ...
end
Хотя, индексы будут идти от 0
до length - 1
, а не наоборот.
Ответ 3
Ну, так как Ruby всегда любит давать вам варианты, которые вы можете делать не только:
arr.reverse.each_with_index do |e, i|
end
но вы также можете сделать:
arr.reverse_each.with_index do |e, i|
end
Ответ 4
Просто
arr.reverse.each_with_index do |node, index|
Ответ 5
Без копирования массива:
(array.size - 1).downto(0) do |index|
node = array[index]
# ...
end