ruby
  1. ruby-blocks

Ruby Blocks

A block is a piece of code that can be passed to a method as an argument. It is a closure in Ruby, meaning it can encapsulate a state that can be accessed from within the block even if it is defined outside of it.

Syntax

Blocks are defined with either do/end or curly braces {}. Here's the syntax for defining blocks:

# With do/end
method_name do |parameter1, parameter2|
  # Code here
end

# With curly braces
method_name { |parameter1, parameter2|
  # Code here
}

Example

# Using a block with Array#each
numbers = [1, 2, 3, 4, 5]
numbers.each do |number|
  puts number ** 2
end

# Using a block with Hash#each
countries = { "USA" => "Washington D.C.", "France" => "Paris", "UK" => "London" }
countries.each { |country, capital| puts "#{country}'s capital is #{capital}" }

Output

1
4
9
16
25
USA's capital is Washington D.C.
France's capital is Paris
UK's capital is London

Explanation

In the first example, we define an array with 5 integers and then call the each method on it. We provide a block that takes number as a parameter and then prints its square. The each method then iterates through the array and yields each element to the block, which then runs the code inside.

In the second example, we define a hash with 3 key-value pairs and then call the each method on it. We provide a block that takes country and capital as parameters and then prints them using string interpolation. The each method then iterates through the hash and yields each key-value pair to the block, which then runs the code inside.

Use

Blocks are often used to encapsulate behavior that can be passed around and reused by other methods. They are commonly used with methods that take an enumerable object as an argument, like each, map, select, and reduce.

Important Points

  • Blocks are closures that can capture and access state defined outside of them.
  • Blocks are defined with either do/end or curly braces {}.
  • Blocks are often used with methods that take an enumerable object as an argument.

Summary

Blocks are an important part of Ruby programming and are frequently used to encapsulate behavior that can be passed around and reused by other methods. They are defined with either do/end or curly braces {} and are often used with methods that take an enumerable object as an argument.

Published on: