[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
的方向,可以这么说。
答案 0 :(得分:1)
i, counter = 0, 1 # initialize index to 0, counter to 1
while(i < a.length && i >= 0) do
puts a[i]
i+= counter # increment counter
counter*= -1 if(condition) # Multiply counter with -1 to reverse it
end
答案 1 :(得分:0)
您可以使用Enumerator
类来创建可以通过数组提供自定义迭代的自定义枚举。在下面的代码中,为了方便起见,我正在修补Array
类(也因为方法与Array#cycle
的相似性),尽管解决方案也可以在没有猴子修补的情况下完成。
class Array
def reversible_cycle
Enumerator.new do |y|
index = 0
direction = :forward
loop do
direction = :backward if index + 1 >= size
direction = :forward if index <= 0
y << self[index]
index += (direction == :forward ? +1 : -1)
end
end
end
end
p [1,2,3,4,5].reversible_cycle.take(9)
#=> [1, 2, 3, 4, 5, 4, 3, 2, 1]
p [1,2,3,4,5].reversible_cycle.take(13)
#=> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5]
p [1,2,3,4,5].reversible_cycle.take(17)
#> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1]
p [1,2,3,4,5].reversible_cycle.take(21)
#=> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5]
对于在不向一个方向完全迭代数组的情况下改变方向的场景,您必须提供一些示例,以便可以看到如何修改上述代码以适应
答案 2 :(得分:0)
嗯,这是你阵列的移动“光标”:
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
答案 3 :(得分:0)
你可以使用Ruby不太受欢迎的flip-flop operator。
arr = [1,2,3,4,5]
sz = arr.size
(2*sz-1).times { |i| puts i==0..i==arr.size-1 ? arr[i] : arr[sz-i-2] }
1
2
3
4
5
4
3
2
1