我想在数组中使用像reverse_each_with_index这样的东西.
例:
array.reverse_each_with_index do |node,index| puts node puts index end
我看到Ruby有every_with_index,但似乎没有什么相反的.有另一种方法吗?
解决方法@H_502_10@
如果你想要数组中的元素的实际索引,你可以这样做
['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','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
['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','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