遍历数组向前然后向后遍历

凯文
[1,2,3,4,5]
=>1,2,3,4,5,4,3,2,1
=>1,2,3,2,3,4,5,4,3 #I need to be able to reverse the iteration at certain points

我首先尝试了类似的方法:

a = [1,2,3,4,5]
a.each {|i|
  if i % 9 == 0
  a.reverse!
}

但这只会反转整个数组,并从其中断的索引开始计数。可以each这么说,我需要改变的方向

金莫·列托(Kimmo Lehto)

好吧,这是数组的移动“光标”:

module Cursor
  def current_index
    @current_index ||= 0
  end

  def step
    @current_index = current_index + direction
    handle_boundary
  end

  def step_back
    @current_index = current_index + (direction * -1)
    handle_boundary
  end

  def handle_boundary
    if current_index == length || current_index == 0
      turn_around
    end
  end

  def direction
    @direction ||= 1
  end

  def turn_around
    @direction = direction * -1
  end

  def current
    self[current_index]
  end
end

这是您的使用方式:

array = [1,2,3,4,5]
arary.extend Cursor
array.current     # returns the item in current position
array.step        # moves a step forward, turns around when it reaches either end of the array
array.step_back   # moves a step backward without switching the direction
array.turn_around # switch the direction

现在您可以随心所欲:D

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章