Ruby Basics : The yield Keyword

In this article, you will learn the basics of yield keyword. We will implement our own version of the Ruby built-in times method to get a better understanding of how it works.

Analogy

Yield

When you are driving, if you see the yield sign, you let other vehicles pass through before you enter the road. In Ruby, the yield keyword yields the flow of control to the code in the block. So, the code in the block is executed and the execution continues after the line containing the yield.

Yield Example

Let's look at an example that uses yield keyword to execute code.

class Actor
  def act
    yield
  end
end

snowy = Actor.new
snowy.act { p 'wag the tail' }

The act method in Actor class has the yield keyword. The yield keyword yields flow of control to the block that calls the act method. In our example, the code between the curly braces is the block that gets executed. This prints:

wag the tail

Code Block

Our simple hail taxi program uses a block with do-end keywords.

3.times do 
  p 'Taxi'
end

The code block is part of the syntax of the method call. The times method is called with the block that prints Taxi.

Implementing times Method

Let's write our version of times method to get a better understanding of the Ruby built-in times method.

class Fixnum
  def my_times
    for i in 1..self
      yield
    end
  end
end

3.my_times do
  p 'Taxi'
end

We re-opened the Fixnum class to define our my_times method. Inside the for loop, we call the block using the yield keyword. The block is a nameless function and has no name, so yield is the only way to call it. You can think of yield keyword as yielding control of flow to the block. We then call my_times method with a block as an implicit argument. This produces the same output.

Fabio Asks

I am getting:

LocalJumpError: no block given (yield)

when I run the code without a block.

class Fixnum
  def my_times
    for i in 1..self
      yield 
    end
  end
end

3.my_times 

You can prevent this error by checking if the block is given.

class Fixnum
  def my_times
    for i in 1..self
      yield if block_given?
    end
  end
end

3.my_times 

Summary

In this article, you learned the basics of yield keyword. We implemented our own version of the Ruby built-in times method to get a better understanding of how it works.


Related Articles


Create your own user feedback survey