Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby syntax: break out from 'each.. do..' block

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?

like image 345
Mellon Avatar asked Dec 14 '11 09:12

Mellon


People also ask

How do you break out of a loop in Ruby?

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.

Is it possible to use each and each in Ruby?

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.

What does break return in Ruby?

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.

How do you stop an infinite loop in Ruby?

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.


1 Answers

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.

like image 68
tbuehlmann Avatar answered Oct 11 '22 22:10

tbuehlmann