Using Blocks in Ruby

Categories:

Recommended

A block is a chunk of code that you associate with a method call. While the method runs, it can invoke (execute) the block one or more times. Methods and blocks work in tandem to process your data. Blocks are a way of encapsulating or packaging statements up and using them wherever you need them. They turn up all over Ruby code.

Blocks are mind-bending stuff. But stick with it!

Even if you’ve programmed in other languages, you’ve probably never seen anything like blocks. But stick with it, because the payoff is big.

Imagine if, for all the methods you have to write for the rest of your career, someone else wrote half of the code for you. For free. They’d write all the tedious stuff at the beginning and end, and just leave a little blank space in the middle for you to insert your code, the clever code, the code that runs your business.

If we told you that blocks can give you that, you’d be willing to do whatever it takes to learn them, right?

Well, here’s what you’ll have to do: be patient, and persistent. We’re here to help. We’ll look at each concept repeatedly, from different angles. We’ll provide exercises for practice. Make sure to do them, because they’ll help you understand and remember how blocks work.

A few hours of hard work now are going to pay dividends for the rest of your Ruby career, we promise. Let’s get to it!

Ruby is an interpretedhigh-levelgeneral-purpose programming language that supports multiple programming paradigms. It was designed with an emphasis on programming productivity and simplicity. In Ruby, everything is an object, including primitive data types. It was developed in the mid-1990s by Yukihiro “Matz” Matsumoto in Japan.

Category:

Attribution

Jay McGavren. Using Blocks in Ruby. https://web.archive.org/web/20201027171026/https://www.oreilly.com/programming/free/files/using-blocks-in-ruby.pdf

VP Flipbook Maker

Convert your work to digital flipbook with VP Online Flipbook Maker! You can also create a new one with the tool. Try it now!