Jeśli chcesz prawdziwy indeks elementu w tablicy można wykonać:
['Seriously', 'Chunky', 'Bacon'].to_enum.with_index.reverse_each do |word, index|
puts "index #{index}: #{word}"
end
wyjściowa:
index 2: Bacon
index 1: Chunky
index 0: Seriously
Można również zdefiniować własne metody 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
Zoptymalizowana wersja
class Array
def reverse_each_with_index &block
(0...length).reverse_each do |i|
block.call self[i], i
end
end
end
Czy możesz mi powiedzieć, jakie wyjście chcesz mieć? –
Czy pytasz, jak użyć (nie) istniejącej metody o nazwie 'reverse_each_with_index', czy chcesz zaimplementować taką, która ma określoną funkcję? Różne części twojego pytania sugerują jedno lub drugie. – sawa