Ruby Array – 使用next和before元素进行反向迭代

如何使用当前元素的next和before元素反向迭代一个数组?

是否可以将each_consreverse_each一起使用?

对的,这是可能的。

 [1,2,3,4,5,6].reverse_each.each_cons(3) { |before, current, next_| p [before, current, next_] } 

版画

 [6, 5, 4] [5, 4, 3] [4, 3, 2] [3, 2, 1] 

 ([nil]+[1,2,3,4,5,6]+[nil]).reverse_each.each_cons(3) { |before, current, next_| p [before, current, next_] } 

版画

 [nil, 6, 5] [6, 5, 4] [5, 4, 3] [4, 3, 2] [3, 2, 1] [2, 1, nil] 

这可能对你有用:

 class Array alias :old_each :each def each reverse.old_each {|e| yield e} end end a = [1,2,3] a.each {|e| print "#{e} "} # => 3 2 1 

请注意,您必须小心这一点,因为出于效率原因,Array会在不使用each方法的情况下重载一些Enumerable方法。

我和我以前的雇主在一个大项目中使用了这个,在我离开前添加它。 男孩,我很高兴离开那里。

编辑:我刚刚想到我可以在上面引用的项目中改进它:

  def each if rand(1000) == 500 reverse.old_each {|e| yield e} else old_each {|e| yield e} end end