airbnb / ruby

Ruby Style Guide

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

return from block

thesmart opened this issue · comments

The style guide ought to include a note about using return in a block.

From StackOverflow answer

Ruby has three constructs:

  1. A block is not an object and is created by { ... } or do ... end.
  2. A proc is a Proc object created by Proc.new or proc.
  3. A lambda is a Proc created by lambda (or proc in Ruby 1.8).

Ruby has three keywords that return from something:

  1. return terminates the method or lambda it is in.
  2. next terminates the block, proc, or lambda it is in.
  3. break terminates the method that yielded to the block or invoked the proc or lambda it is in.

In lambdas, return behaves like next, for whatever reason. next and break are named the way they are because they are most commonly used with methods like each, where terminating the block will cause the iteration to resume with the next element of the collection, and terminating each will cause you to break out of the loop.

Perhaps the following recommendation:

Avoid return in procs/blocks because return terminates the method calling a proc/block:

def all_even?
  self.numbers.all? do |num| 
    if num % 2 == 0
      # This will cause `all_even?` to return `true` when the first even number is reached
      return true
    else 
      return false
    end
  end
end
def all_even?
  self.numbers.all? do |num| 
    if num % 2 == 0
      # Proceed to the next iteration
      next true
    else 
     # Stop iterating, there is at least one odd number
      break false
    end
  end
end

I don't think we should have this recommendation. This behavior in Ruby is by design and is normal practice because it's very common to return from a block. It allows you do refactor code within a method (e.g., move code into or out of a block) without changing the behavior of the code.

Ok. :)