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

Mellon picture Mellon · Dec 14, 2011 · Viewed 87.1k times · Source

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?

Answer

tbuehlmann picture tbuehlmann · Dec 14, 2011

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.