Ruby 语法:从 'each.. do..' 块中跳出 [英] Ruby syntax: break out from 'each.. do..' block
问题描述
我正在开发 Ruby on Rails 应用程序.我的问题更多是关于 Ruby 语法的.
I am developing a Ruby on Rails app. My question is more about Ruby syntax.
我有一个带有类方法 self.check
的模型类:
I have a model class with a class method self.check
:
class Cars < ActiveRecord::Base
...
def self.check(name)
self.all.each do |car|
#if result is true, break out from the each block, and return the car how to...
result = SOME_CONDITION_MEET?(car) #not related with database
end
puts "outside the each block."
end
end
我想停止/突破 each
块一次 result
是 true(那就是如果 car.name
与 name
参数相同,则打破 each
块once) 并返回 car
导致 true 结果.如何在 Ruby 代码中突围?
I would like to stop/break out from the each
block once the result
is true (that's break the each
block if car.name
is the same as the name
parameter once) AND return the car
which cause the true result. How to break out in Ruby code?
推荐答案
您可以使用 break
关键字中断.例如
You can break with the break
keyword. For example
[1,2,3].each do |i|
puts i
break
end
将输出1
.或者如果你想直接返回值,使用return
.
will output 1
. Or if you want to directly return the value, use return
.
自从你更新了问题,这里是代码:
Since you updated the question, here the code:
class Car < ActiveRecord::Base
# …
def self.check(name)
self.all.each do |car|
return car if some_condition_met?(car)
end
puts "outside the each block."
end
end
虽然你也可以使用 Array#detect
或 Array#any?
来达到这个目的.
Though you can also use Array#detect
or Array#any?
for that purpose.
这篇关于Ruby 语法:从 'each.. do..' 块中跳出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!