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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)