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

you can use include? method.

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

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


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.


You can use break but what your are trying to do could be done much easier, like this:

def self.check(name)
  return false if self.find_by_name(name).nil?
  return true
end

This uses the database. You are trying to use Ruby at a place the database can deal with it better.

You can also use break conditional:

break if (car.name == name)

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.