0% found this document useful (0 votes)
30 views

Blocks How They Are Used How To Incorporate Them Into Your Own Methods

Blocks are chunks of code that can be passed into methods. They are enclosed in curly braces or with do/end keywords. Blocks can accept arguments and are often used as iterators. When incorporating blocks into your own methods, you can either use them implicitly by checking for a block with block_given? and yielding to the block, or explicitly by adding an ampersand to the last parameter and calling the block.

Uploaded by

JITENDRA TIWARI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Blocks How They Are Used How To Incorporate Them Into Your Own Methods

Blocks are chunks of code that can be passed into methods. They are enclosed in curly braces or with do/end keywords. Blocks can accept arguments and are often used as iterators. When incorporating blocks into your own methods, you can either use them implicitly by checking for a block with block_given? and yielding to the block, or explicitly by adding an ampersand to the last parameter and calling the block.

Uploaded by

JITENDRA TIWARI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

In this lecture, we will discuss…

² Blocks
² How they are used
² How to incorporate them into your own methods
Blocks
² Chunks of code
•  Enclosed between either curly braces ({}) or the
keywords do and end
•  Passed to methods as last “parameter”
Blocks

² Convention:
•  Use{}when block content is a single line
•  Use do and end when block content spans multiple
lines
²  Often used as iterators
Blocks
²  Can accept arguments

Often accepts parameter(s)


between ||
Coding with blocks
² Two ways to configure a block in your own method
Implicit
•  Use block_given? to see if block was passed in
•  Use yield to “call” the block

Explicit
•  Use & in front of the last “parameter”
•  Use call method to call the block
Implicit
²  Need to check “block_given?”
•  Otherwise, an exception is thrown
Explicit
²  Should check if the block is nil?
Summary
² Blocks are just code that you can pass into methods
² When incorporating into your own methods:
•  Either use blocks implicitly
•  Or call them explicitly

What’s next?
² Files and Environment Variables

You might also like