0
0
Rubyprogramming~5 mins

Block syntax (do..end and curly braces) in Ruby

Choose your learning style9 modes available
Introduction

Blocks let you group code to run later or multiple times. They make your code cleaner and easier to reuse.

When you want to repeat actions for each item in a list.
When you want to run some code only inside a method call.
When you want to pass a small piece of code to another method.
When you want to organize your code clearly without making a new method.
Syntax
Ruby
method_name do
  # code here
end

# or

method_name { # code here }

Use do..end for multi-line blocks.

Use curly braces { } for single-line blocks.

Examples
This prints "Hello" three times using do..end block.
Ruby
3.times do
  puts "Hello"
end
This does the same as above but uses curly braces for a single-line block.
Ruby
3.times { puts "Hi" }
This goes through each number and prints double its value using do..end.
Ruby
numbers = [1, 2, 3]
numbers.each do |n|
  puts n * 2
end
Same as above but with curly braces for a short block.
Ruby
numbers.each { |n| puts n * 2 }
Sample Program

This program counts from 1 to 5 using a do..end block and then prints fruit names in uppercase using a curly braces block.

Ruby
5.times do |i|
  puts "Count: #{i + 1}"
end

["apple", "banana", "cherry"].each { |fruit| puts fruit.upcase }
OutputSuccess
Important Notes

Blocks are anonymous chunks of code you can pass to methods.

Curly braces have higher precedence than do..end, so use them carefully in complex expressions.

Blocks can take parameters inside pipes | | to use values from the method.

Summary

Blocks group code to run inside methods.

Use do..end for multi-line blocks and { } for single-line blocks.

Blocks can take parameters to work with data from the method.