O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Executing Blocks with the yield Keyword

When you see yield anywhere in a Ruby block, you should think “execute the block.” Try out the following in irb:

 >>​ ​def​ do_it
 >>​ ​yield
 >>​ ​end
 =>​ ​:do_it

This is a pretty plain-looking piece of code that just executes any block you give it:

 >>​ do_it { puts ​"I'm doing it"​ }
 I'm doing it
 =>​ ​nil

Outputting a string doesn’t return any value. In other words, this block is executed merely for its side effects. Now, let’s make a block that returns a value and pass it into the do_it method:

 >>​ do_it { [1,2,3] << 4 }
 =>​ [1, 2, 3, 4]

What happens when we don’t pass in a block to do_it?

 >>​ do_it
 LocalJumpError: no block given (yield)
  from (irb):28:in `do_it'

irb helpfully ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required