Ruby Syntax: Break Out from 'Each.. Do..' Block

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.

How to break out from a ruby block?

Use the keyword next. If you do not want to continue to the next item, use break.

When next is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:

f.each do |line|              # Iterate over the lines in file f
next if line[0,1] == "#" # If this line is a comment, go to the next
puts eval(line)
end

When used in a block, break transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:

f.each do |line|             # Iterate over the lines in file f
break if line == "quit\n" # If this break statement is executed...
puts eval(line)
end
puts "Good bye" # ...then control is transferred here

And finally, the usage of return in a block:

return always causes the enclosing method to return, regardless of how deeply nested within blocks it is (except in the case of lambdas):

def find(array, target)
array.each_with_index do |element,index|
return index if (element == target) # return from find
end
nil # If we didn't find the element, return nil
end

Does 'any?' break from the loop when a match is found?

Yes, it does break the loop. One does not need to dig into c code to check that:

[1,2,3].any? { |e| puts "Checking #{e}"; e == 2 }
# Checking 1
# Checking 2
#⇒ true

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
next if a.even?
puts a
end

prints:

1
3
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

Break from block based on time

Since you're unlikely to get to that line at exactly 60 seconds past the start, try:

break if Time.now > @start_time + 60

escaping the .each { } iteration early in Ruby

While the break solution works, I think a more functional approach really suits this problem. You want to take the first 10 elements and print them so try

items.take(10).each { |i| puts i.to_s }


Related Topics



Leave a reply



Submit