I am developing a Ruby on Rails app. My question is more about Ruby syntax.
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
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?
In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.
How does each work in Ruby? each is just another method on an object. That means that if you want to iterate over an array with each , you're calling the each method on that array object. It takes a list as it's first argument and a block as the second argument.
break is called from inside a loop. It will put you right after the innermost loop you are in. return is called from within methods. It will return the value you tell it to and put you right after where it was called.
This means that the loop will run forever ( infinite loop ). To stop this, we can use break and we have used it. if a == "n" -> break : If a user enters n ( n for no ), then the loop will stop there. Any other statement of the loop will not be further executed.
You can break with the break
keyword. For example
[1,2,3].each do |i| puts i break end
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
Though you can also use Array#detect
or Array#any?
for that purpose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With