迴圈控制與休息下一步和重做
可以使用 break
,next
和 redo
語句來控制 Ruby 塊的執行流程。
break
break
語句將立即退出塊。將跳過塊中的任何剩餘指令,迭代將結束:
actions = %w(run jump swim exit macarena)
index = 0
while index < actions.length
action = actions[index]
break if action == "exit"
index += 1
puts "Currently doing this action: #{action}"
end
# Currently doing this action: run
# Currently doing this action: jump
# Currently doing this action: swim
next
next
語句將立即返回到塊的頂部,並繼續下一次迭代。將跳過塊中的任何剩餘指令:
actions = %w(run jump swim rest macarena)
index = 0
while index < actions.length
action = actions[index]
index += 1
next if action == "rest"
puts "Currently doing this action: #{action}"
end
# Currently doing this action: run
# Currently doing this action: jump
# Currently doing this action: swim
# Currently doing this action: macarena
redo
redo
語句將立即返回到塊的頂部,並重試相同的迭代。將跳過塊中的任何剩餘指令:
actions = %w(run jump swim sleep macarena)
index = 0
repeat_count = 0
while index < actions.length
action = actions[index]
puts "Currently doing this action: #{action}"
if action == "sleep"
repeat_count += 1
redo if repeat_count < 3
end
index += 1
end
# Currently doing this action: run
# Currently doing this action: jump
# Currently doing this action: swim
# Currently doing this action: sleep
# Currently doing this action: sleep
# Currently doing this action: sleep
# Currently doing this action: macarena
Enumerable
迭代
除了迴圈之外,這些語句還使用了 Enumerable 迭代方法,例如 each
和 map
:
[1, 2, 3].each do |item|
next if item.even?
puts "Item: #{item}"
end
# Item: 1
# Item: 3
阻止結果值
在 break
和 next
語句中,可以提供一個值,並將其用作塊結果值:
even_value = for value in [1, 2, 3]
break value if value.even?
end
puts "The first even value is: #{even_value}"
# The first even value is: 2