Professional Documents
Culture Documents
Blocks How They Are Used How To Incorporate Them Into Your Own Methods
Blocks How They Are Used How To Incorporate Them Into Your Own Methods
² 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
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