Óla*_*age 5 ruby each conditional
假设我在Ruby中有这个循环.
@list.each { |i|
  puts i
  if i > 10
    break
  end
}
我希望在列表中循环直到满足条件.
这让我觉得"un Ruby'ish",因为我是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}
| 归档时间: | 
 | 
| 查看次数: | 4989 次 | 
| 最近记录: |