Double yields

1208 views

What is the return value of the following Ruby code?

def sum
  n = 0

  n += yield
  n += yield

  n
end

sum { 42 } # => ???

The correct answer is

0

It raises SyntaxError

84

42

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

The yield keyword — in association with a block — allows the passing of a set of additional instructions during a method invocation.

This mechanism allows you to customize a method depending on your needs.

What’s a block?

A block is part of the Ruby method syntax.

This means that when a block is recognized by the Ruby parser it’ll be associated with the invoked method and replace yields in the method

def multiple_yields
  yield
  yield
end

multiple_yields { puts "multiple yields" }

produces

multiple yields
multiple yields

The code inside the block will be "called" for each yield in the method definition.
Whether there is one or more calls.

So

def sum
  n = 0

  n += yield # => n = 0 + 42
  n += yield # => n = 42 + 42

  n # => 84
end

sum { 42 }

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©