How can I return something early from a block?

ryeguy picture ryeguy · Mar 25, 2010 · Viewed 29.7k times · Source

If I wanted to do something like this:

collection.each do |i|
   return nil if i == 3

   ..many lines of code here..
end

How would I get that effect? I know I could just wrap everything inside the block in a big if statement, but I'd like to avoid the nesting if possible.

Break would not work here, because I do not want to stop iteration of the remaining elements.

Answer

sepp2k picture sepp2k · Mar 25, 2010

next inside a block returns from the block. break inside a block returns from the function that yielded to the block. For each this means that break exits the loop and next jumps to the next iteration of the loop (thus the names). You can return values with next value and break value.