Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return something early from a block?

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.

like image 753
ryeguy Avatar asked Mar 25 '10 17:03

ryeguy


People also ask

Can you return in a block Ruby?

You cannot do that in Ruby. The return keyword always returns from the method or lambda in the current context. In blocks, it will return from the method in which the closure was defined. It cannot be made to return from the calling method or lambda.

What is return in Ruby?

Explicit return Ruby provides a keyword that allows the developer to explicitly stop the execution flow of a method and return a specific value.


3 Answers

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.

like image 160
sepp2k Avatar answered Oct 14 '22 09:10

sepp2k


#!/usr/bin/ruby

collection = [1, 2, 3, 4, 5 ]

stopped_at = collection.each do |i|
   break i if i == 3

   puts "Processed #{i}"
end

puts "Stopped at and did not process #{stopped_at}"
like image 25
JD. Avatar answered Oct 14 '22 11:10

JD.


In this instance, you can use break to terminate the loop early:

collection.each do |i|
  break if i == 3
  ...many lines
end

...of course, this is assuming that you're not actually looking to return a value, just break out of the block.

like image 42
Sniggerfardimungus Avatar answered Oct 14 '22 11:10

Sniggerfardimungus