0
0
Rubyprogramming~5 mins

Why blocks are fundamental to Ruby

Choose your learning style9 modes available
Introduction

Blocks let you group code to run later or many times. They make Ruby flexible and easy to write.

When you want to repeat an action for each item in a list.
When you want to run some code only if a condition is true.
When you want to pass a small piece of code to a method to customize its behavior.
When you want to delay running some code until later.
When you want to write cleaner and shorter code by avoiding repetition.
Syntax
Ruby
method_name do
  # code here
end

# or with braces for single line blocks
method_name { # code here }

Blocks are chunks of code between do...end or curly braces {...}.

They can be passed to methods and run inside those methods.

Examples
This runs the block 3 times, printing "Hello!" each time.
Ruby
3.times do
  puts "Hello!"
end
This goes through each number in the list and prints double its value.
Ruby
[1, 2, 3].each { |num| puts num * 2 }
This method runs the block passed to it if there is one.
Ruby
def greet
  yield if block_given?
end

greet { puts "Hi there!" }
Sample Program

This program counts from 1 to 5, printing each number with the word "Count:".

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

Blocks help keep your code short and easy to read.

You can pass blocks to methods to customize what they do.

Blocks can take parameters, like the i in the example, to work with data.

Summary

Blocks are pieces of code you can pass to methods.

They let you run code multiple times or at specific moments.

Blocks make Ruby code flexible and clean.