假设我在 Ruby 中有以下 each 循环。
@list.each { |i|
puts i
if i > 10
break
end
}
我希望能在列表中循环直到满足条件。
这让我感到不太符合Ruby的风格,因为我是Ruby新手,有没有一种Ruby的方式来实现这个呢?
@list.each { |i|
puts i
if i > 10
break
end
}
我希望能在列表中循环直到满足条件。
这让我感到不太符合Ruby的风格,因为我是Ruby新手,有没有一种Ruby的方式来实现这个呢?
Enumerable#detect
或者 Enumerable#take_while
,具体取决于你想要的结果。@list.detect { |i|
puts i
i > 10
} # Returns the first element greater than 10, or nil.
正如其他人所指出的,更好的做法是首先进行子选择,然后再对其进行操作,例如:
@list.take_while{ |i| i <= 10 }.each{|i| puts i}
@list.take_while { |i| i <= 11 }.each { |i| puts i }
each
,然后仅在与条件匹配的元素上执行块? - asymmetric