0
0
Rubyprogramming~5 mins

Block parameters in Ruby

Choose your learning style9 modes available
Introduction

Block parameters let you give names to values passed into a block. This helps you use those values inside the block easily.

When you want to work with each item in a list inside a block.
When you want to pass values from a method to a block and use them.
When you want to write reusable code that works with different inputs.
When you want to make your code clearer by naming the values inside a block.
Syntax
Ruby
collection.each do |parameter1, parameter2|
  # code using parameter1 and parameter2
end

Block parameters go between vertical bars | | right after do or {.

You can have one or more parameters separated by commas.

Examples
This example uses one block parameter num to double each number.
Ruby
numbers = [1, 2, 3]
numbers.each do |num|
  puts num * 2
end
This example uses two block parameters number and word to access each pair's elements.
Ruby
pairs = [[1, 'one'], [2, 'two']]
pairs.each do |number, word|
  puts "#{number} means #{word}"
end
Sample Program

This program prints a sentence for each fruit using a block parameter named fruit.

Ruby
fruits = ['apple', 'banana', 'cherry']
fruits.each do |fruit|
  puts "I like #{fruit}s"
end
OutputSuccess
Important Notes

If you forget block parameters, you can't access the values inside the block.

You can use either do |params| ... end or curly braces { |params| ... } for blocks.

Summary

Block parameters name the values passed into a block.

They go inside | | after do or {.

Use them to work with each item or value inside the block.