Blocks in Ruby Language
Ruby is known for its flexibility and readability, and one of the language’s most powerful features is it
s support for blocks. Blocks are chunks of code that can be associated with method calls, offering a way to encapsulate and execute code within the context of a method. This feature allows for a more concise and elegant code structure. In this post, we’ll explore what blocks are and how they work in Ruby with examples.What Are Blocks in Ruby?
Blocks in Ruby are not objects like procs or lambdas but are pieces of code that can be passed to methods as arguments. They are often used for iterating through collections, executing code conditionally, or creating custom iterators. Blocks are defined within a do..end
or curly braces {}
.
Basic Block Syntax in Ruby
Here is a basic block syntax using do..end
:
3.times do
puts "Hello, world!"
end
In this example, do
marks the beginning of the block, and end
indicates its end. The code within the block is executed three times, printing “Hello, world!” on each iteration.
Alternatively, you can use curly braces for one-liner blocks:
3.times { puts "Hello, world!" }
Passing Blocks to Methods in Ruby
One of the most common use cases for blocks in Ruby is when working with enumerable methods like each
, map
, and select
. These methods can take a block as an argument, which is then executed for each element in the collection.
Let’s see an example using each
:
numbers = [1, 2, 3, 4, 5]
numbers.each do |number|
puts "Number: #{number}"
end
In this case, the block is executed for each element in the numbers
array, printing each number.
Custom Blocks in Ruby
You can also create custom methods that yield to a block. To do this, use the yield
statement within the method:
def greet
puts "Hello, this is before the yield statement."
yield if block_given?
puts "This is after the yield statement."
end
greet do
puts "Custom block: Hello, world!"
end
In this example, the greet
method yields control to the block passed as an argument, allowing you to inject custom code into the method.
Lambdas vs. Blocks in Ruby
It’s important to note that blocks are not the same as lambdas. Blocks are more lightweight and cannot be stored in variables or passed around, whereas lambdas are objects with a few key differences, such as strict argument count. Understanding these differences is crucial when working with Ruby’s powerful features.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.