Ruby数组reverse_each_with_index

use*_*770 16 ruby

我想reverse_each_with_index在数组上使用类似的东西.

例:

array.reverse_each_with_index do |node,index|
  puts node
  puts index
end
Run Code Online (Sandbox Code Playgroud)

我看到Ruby有,each_with_index但似乎并没有相反.还有另一种方法吗?

Bue*_*und 46

如果你想要数组中元素的真实索引,你可以这样做

['Seriously', 'Chunky', 'Bacon'].to_enum.with_index.reverse_each do |word, index|
  puts "index #{index}: #{word}"
end
Run Code Online (Sandbox Code Playgroud)

输出:

index 2: Bacon
index 1: Chunky
index 0: Seriously
Run Code Online (Sandbox Code Playgroud)

您还可以定义自己的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
Run Code Online (Sandbox Code Playgroud)

优化版

class Array
  def reverse_each_with_index &block
    (0...length).reverse_each do |i|
      block.call self[i], i
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


Ser*_*sev 20

首先reverse是数组,然后使用each_with_index:

array.reverse.each_with_index do |element, index|
  # ...
end
Run Code Online (Sandbox Code Playgroud)

虽然,指数会从0length - 1,不是周围的其他方式.

  • 这会创建数组的副本,不是吗? (3认同)

Ant*_*one 8

好吧,因为Ruby总是喜欢给你选项,你不仅可以这样做:

arr.reverse.each_with_index do |e, i|

end
Run Code Online (Sandbox Code Playgroud)

但你也可以这样做:

arr.reverse_each.with_index do |e, i|

end
Run Code Online (Sandbox Code Playgroud)

  • `arr.reverse_each.with_index 做 |e, i| end` 不适用于操作的要求。这将产生前序索引 [0,1,2 等] (3认同)

Pav*_*eev 6

不复制数组:

(array.size - 1).downto(0) do |index|
  node = array[index]
  # ...
end
Run Code Online (Sandbox Code Playgroud)