Ruby数组reverse_each_with_index
发布时间:2020-12-16 19:49:34 所属栏目:百科 来源:网络整理
导读:我想在数组中使用像reverse_each_with_index这样的东西. 例: array.reverse_each_with_index do |node,index| puts node puts indexend 我看到Ruby有every_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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |