Ruby数组reverse_each_with_index

我想在数组中使用像reverse_each_with_index这样的东西.

例:

array.reverse_each_with_index do |node,index|
  puts node
  puts index
end

我看到Ruby有every_with_index,但似乎没有什么相反的.有另一种方法吗?

解决方法

如果你想要数组中的元素的实际索引,你可以这样做
['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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...