红宝石中有each_if吗?

Óla*_*age 5 ruby each conditional

假设我在Ruby中有这个循环.

@list.each { |i|
  puts i

  if i > 10
    break
  end
}
Run Code Online (Sandbox Code Playgroud)

我希望在列表中循环直到满足条件.

这让我觉得"un Ruby'ish",因为我是Ruby的新手,有没有Ruby方法可以做到这一点?

Mar*_*une 6

您可以使用Enumerable#detectEnumerable#take_while取决于您想要的结果.

@list.detect { |i|
  puts i
  i > 10
} # Returns the first element greater than 10, or nil.
Run Code Online (Sandbox Code Playgroud)

正如其他人所指出的那样,更好的风格是首先进行子选择然后对其采取行动,例如:

@list.take_while{ |i| i <= 10 }.each{|i| puts i}
Run Code Online (Sandbox Code Playgroud)