Last Updated: March 03, 2018
·
1.742K
· Youssef Kababe

Ruby's yield & blocks

Learning blocks and the yield statement can be a bit confusing for beginners, the code bellow shows how the times method receives a block and uses the yield statement to interpret what's inside that block. I'm sharing this because it really helped me understand how Ruby works.

In this example we will define a french version of the times method called "fois" (fois means times in french) inside the Integer class:

class Integer
  def fois
    for i in 0...self
      # self is referring to the current object, when we call
      # this method on 6 for example (6.fois) then self
      # will take the value 6
      yield i
      # the yield statement passes i as a parameter to the block,
      # which in turn uses it to perform some actions
    end
    self
    # this is equivalent to "return self", the method should
    # return the current object at the end
  end
end

Now you can use the new method we defined above like you usually use the times method:

5.fois { |x| puts x }
2.fois { puts "Ruby is awesome" }

What we did above is also known as "Monkey Patching", it's when you open a Ruby class and define your new methods inside of it. I hope this has helped you understand the blocks & yield a bit more!

3 Responses
Add your response

There is better option:

alias_method :fois, :times
over 1 year ago ·

Yes, there's always a better option in Ruby, but the point from my tip is to understand how the times method uses the yield statement and the block.

over 1 year ago ·

Thanks for making this short.

over 1 year ago ·