0
0
RubyHow-ToBeginner · 3 min read

How to Use Block in Ruby: Simple Guide with Examples

In Ruby, a block is a chunk of code enclosed in { } or do...end that you can pass to methods to run later. You use blocks by placing them after a method call, and inside the method, you can execute the block with yield or by calling a block parameter.
📐

Syntax

A block in Ruby is written either with curly braces { } for single-line blocks or with do...end for multi-line blocks. You attach a block to a method call by placing it right after the method's parentheses or arguments. Inside the method, you can run the block using yield or by accepting a block parameter with &block and calling block.call.

  • Curly braces: Used for short, single-line blocks.
  • do...end: Used for longer, multi-line blocks.
  • yield: Runs the block passed to the method.
  • &block: Captures the block as a Proc object to call explicitly.
ruby
def greet
  yield
end

greet { puts "Hello from the block!" }
Output
Hello from the block!
💻

Example

This example shows a method repeat that takes a number and a block. It runs the block the given number of times using yield. The block prints a message each time it runs.

ruby
def repeat(times)
  times.times do |i|
    yield(i + 1)
  end
end

repeat(3) do |count|
  puts "This is repetition number #{count}"
end
Output
This is repetition number 1 This is repetition number 2 This is repetition number 3
⚠️

Common Pitfalls

Common mistakes when using blocks include forgetting to pass a block when the method expects one, or calling yield without checking if a block was given, which causes an error. Also, confusing when to use { } versus do...end can affect readability but not functionality.

Always check if a block is given with block_given? before calling yield to avoid errors.

ruby
def safe_greet
  if block_given?
    yield
  else
    puts "No block given!"
  end
end

safe_greet { puts "Hello!" }
safe_greet
Output
Hello! No block given!
📊

Quick Reference

ConceptDescriptionExample
Block syntaxUse { } for single-line, do...end for multi-linemethod { puts 'Hi' } or method do puts 'Hi' end
Calling blockUse yield inside method to run blockyield
Block parameterCapture block as &block to call explicitlydef m(&block); block.call; end
Check blockUse block_given? to avoid errorsif block_given?; yield; end

Key Takeaways

Blocks are chunks of code passed to methods using { } or do...end.
Use yield inside methods to run the passed block.
Check with block_given? before calling yield to avoid errors.
You can capture blocks as &block parameters to call them explicitly.
Curly braces are for short blocks; do...end is for longer blocks.