微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/ruby/272015.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐