Introduction
Blocks let you group code to run later or many times. They make Ruby flexible and easy to write.
Blocks let you group code to run later or many times. They make Ruby flexible and easy to write.
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.
3.times do puts "Hello!" end
[1, 2, 3].each { |num| puts num * 2 }
def greet yield if block_given? end greet { puts "Hi there!" }
This program counts from 1 to 5, printing each number with the word "Count:".
5.times do |i| puts "Count: #{i + 1}" end
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.
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.
def greet
yield 'Ruby'
end
greet { |name| puts "Hello, #{name}!" }def repeat
3.times do
yield
end
end
repeat { puts 'Hi' }Pass the test and this pattern moves unknown