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

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


You can break with the break keyword. For example

[1,2,3].each do |i|  puts i  breakend

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."  endend

Though you can also use Array#detect or Array#any? for that purpose.


I provide a bad sample code. I am not directly find or check something from database. I just need a way to break out from the "each" block if some condition meets once and return that 'car' which cause the true result.

Then what you need is:

def check(cars, car_name)  cars.detect { |car| car.name == car_name }end

If you wanted just to know if there was any car with that name then you'd use Enumerable#any?. As a rule of thumb, use Enumerable#each only to do side effects, not perform logic.


you can use include? method.

def self.check(name)  cars.include? nameend

include? returns true if name is present in the cars array else it returns false.