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 ...

Get Mastering Ruby Closures now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.