我想reverse_each_with_index在数组上使用类似的东西.
例:
array.reverse_each_with_index do |node,index|
  puts node
  puts index
end
我看到Ruby有,each_with_index但似乎并没有相反.还有另一种方法吗?
Bue*_*und 46
如果你想要数组中元素的真实索引,你可以这样做
['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
Ser*_*sev 20
首先reverse是数组,然后使用each_with_index:
array.reverse.each_with_index do |element, index|
  # ...
end
虽然,指数会从0到length - 1,不是周围的其他方式.
好吧,因为Ruby总是喜欢给你选项,你不仅可以这样做:
arr.reverse.each_with_index do |e, i|
end
但你也可以这样做:
arr.reverse_each.with_index do |e, i|
end
不复制数组:
(array.size - 1).downto(0) do |index|
  node = array[index]
  # ...
end