Chapter 14
Blocks and Procs

This is definitely one of the coolest features of Ruby. Some other languages have this feature, though they may call it something else (like closures), but most of the more popular ones don’t, and it’s a shame. And, in any case, Ruby makes it so pretty with its cute little syntax!

What is this cool new thing? It’s the ability to take a block of code (code in between do and end), wrap it up in an object (called a proc), store it in a variable or pass it to a method, and run the code in the block whenever you feel like it (more than once, if you want). So, it’s kind of like a method itself, except it isn’t bound to an object (it is an object), and you can store it or pass it around like you can with any object. I think it’s example time:

toast = Proc.new ​do
puts ​'Cheers!'
end
toast.call
toast.call
toast.call
Cheers!
Cheers!
Cheers!

I created a proc (which I think is supposed to be short for procedure, but far more important, it rhymes with block) that held the block of code, and then I called the proc three times. As you can see, it’s a lot like a method.

Actually, it’s even more like a method than I have shown you, because blocks can take parameters:

do_you_like = Proc.new ​do​ |good_stuff|
puts ​"I *really* like ​#{good_stuff}​!"
end
do_you_like.call ​'chocolate'
do_you_like.call ​'Ruby'
I *really* like chocolate!
I *really* like Ruby!

OK, so we see what blocks and procs are, and how to use them, but what’s the point? Why not just use methods? Well, it’s because there are some things you just can’t do with methods. In particular, you can’t pass methods into other methods (but you can pass procs into methods), and methods can’t return other methods (but they can return procs). This is simply because procs are objects; methods aren’t.

(By the way, is any of this looking familiar? Yep, you’ve seen blocks before…when you learned about iterators. But let’s talk more about that in a bit.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181