Jak*_*mpl 557
用途next
:
(1..10).each do |a|
next if a.even?
puts a
end
Run Code Online (Sandbox Code Playgroud)
打印:
1
3
5
7
9
Run Code Online (Sandbox Code Playgroud)
有关更多的凉意退房还redo
和retry
.
也适用于这样的朋友times
,upto
,downto
,each_with_index
,select
,map
和其他迭代器(和更普遍块).
有关详细信息,请参阅http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.
Ash*_*she 48
next
- 它就像return
,但是对于块!(所以你可以在任何proc
/中使用它lambda
.)
这意味着你也可以说从块中next n
"返回" n
.例如:
puts [1, 2, 3].map do |e|
next 42 if e == 2
e
end.inject(&:+)
Run Code Online (Sandbox Code Playgroud)
这会产生46
.
请注意,return
始终从最近的def
,而不是块返回; 如果没有周围def
,return
ing是一个错误.
return
故意在块内使用可能会造成混淆.例如:
def my_fun
[1, 2, 3].map do |e|
return "Hello." if e == 2
e
end
end
Run Code Online (Sandbox Code Playgroud)
my_fun
将导致"Hello."
,而不是[1, "Hello.", 2]
因为return
关键字属于外部def
,而不是内部块.