Functions
Ruby Blocks
Using Blocks
Ruby blocks use do-end or {} for inline logic.
Introduction to Ruby Blocks
Ruby blocks are a powerful feature of the language that allow you to group statements together. They can be used to pass chunks of code to methods and are often utilized in iterators. Blocks can be defined using either the do-end
syntax or curly braces {}
. They are not objects, but they can be converted into objects of class Proc
.
Syntax of Ruby Blocks
Blocks can be created in two ways in Ruby: using do-end
or curly braces {}
. The choice between these two is mostly stylistic, with do-end
often used for multi-line blocks and {}
for single-line blocks. Here's how you can define both:
Yielding to a Block
Ruby methods can yield to a block, allowing you to execute the block's code within the method. This is done using the yield
keyword. If a block is given when the method is called, the block will be executed. Here's an example:
Block Parameters
Blocks can take parameters, which are defined between pipes | |
. These parameters are typically used to work with elements of a collection. For example:
Using Blocks for Iteration
Blocks are commonly used in Ruby for iterating over collections. Most Ruby collection classes, such as Array
and Hash
, have methods that accept blocks. The each
method is one of the most frequently used iteration methods:
Conclusion
Ruby blocks are a versatile feature that allow you to write concise and flexible code. They are essential for many Ruby idioms and are a critical part of the language's expressive power. Understanding how to use blocks effectively will greatly enhance your ability to write efficient Ruby code.