🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Ruby Blocks, Yield, and Enumerable— Complete Beginner Guide

Ruby BasicsRuby Blocks, Yield, and Enumerable🟢 Free Lesson

Ruby Blocks, Yield, and the Enumerable Spirit— Complete Beginner Guide

Learning Objectives

  • Write blocks using both do end and brace syntax
  • Pass parameters into blocks
  • Call blocks from methods using yield
  • Supply default behavior when no block is given
  • Recognize how Enumerable uses blocks throughout Ruby

What Is a Block

A block is a chunk of code you attach to a method call. It defines what should happen for each item or during the method's work. Blocks are not objects by themselves until you convert them, which you will explore with procs later.

3.times do
  puts "Block running"
end

You can also write short single-line blocks with curly braces:

[1, 2, 3].each { |n| puts n }

Community style prefers do end for multi-line blocks and braces for short, inline expressions.

Block Parameters

Blocks receive values from the method that yields them.

names = ["Ada", "Grace", "Linus"]

names.each do |name|
  puts "Hello, #{name}"
end

The pipe-delimited name variable takes a different value on each iteration. If you do not need the value, you may omit the parameters entirely.

Multiple block parameters

pairs = { a: 1, b: 2 }

pairs.each do |key, value|
  puts "#{key} => #{value}"
end

Methods pass as many values as your block declares; extra values are ignored in common cases.

How Yield Works

When a method needs to hand control to your block, it calls yield.

def run_twice
  puts "Before yield"
  yield
  puts "After yield"
end

run_twice do
  puts "Inside the block"
end

The method pauses at yield, executes your block, then resumes. The same method can accept different blocks on different calls, making it highly reusable.

Passing values through yield

def shout(word)
  yield word.upcase
end

shout("hello") do |text|
  puts text + "!!!"
end

Arguments given to yield arrive as the block's parameters.

Handling a Missing Block

Sometimes you want optional customization. check if a block exists before yielding:

def report(value)
  puts "Value: #{value}"
  yield if block_given?
end

report(10)
report(20) { |v| puts "Squared: #{v * v}" }

block_given? returns true only when the caller attached a block, letting one method serve both simple and customized calls.

The Enumerable Spirit

Enumerable is a module that gives collections a consistent toolkit of block-based methods. Arrays include Enumerable automatically, and hashes and ranges support similar behaviors.

Core Enumerable methods

MethodWhat it does with your block
eachVisits every element
mapTransforms each element into a new array
selectKeeps elements where the block is true
rejectDrops elements where the block is true
findReturns the first match
reduceFolds elements into a single result

Because so many methods rely on blocks, mastering blocks unlocks nearly all of Ruby's collection programming style.

Chaining blocks

numbers = [1, 2, 3, 4, 5, 6]

result = numbers.select { |n| n.even? }.map { |n| n * n }
puts result.inspect

First, even numbers are filtered; then each is squared. Chaining keeps transformations declarative and easy to read top to bottom.

Blocks Capture Local Context

Blocks remember the surrounding local variables where they were written. This lexical capture means you can build blocks that use data defined nearby without passing everything through parameters.

prefix = "Log:"

def print_with_prefix(items, prefix)
  items.each do |item|
    yield "#{prefix} #{item}"
  end
end

print_with_prefix(["a", "b"], prefix) { |line| puts line }

Blocks make it easy to inject small pieces of behavior exactly where they are needed.

Common Mistakes

  • Confusing do end with methods; blocks only run when a method yields or calls them
  • Expecting yield to work outside a method body
  • Writing deeply nested blocks when separate named methods would be clearer
  • Forgetting block_given? checks when the block should be optional

Recognizing these patterns early keeps your methods flexible and readable.

Blocks as Lightweight Functions

One of the most powerful aspects of blocks is that they let you inject behavior into methods without defining a separate named function first. When you pass a block to sort, you are telling Ruby exactly how to compare elements. When you pass a block to each, you describe what to do with every element. This style keeps your code focused on the task at hand rather than on ceremony.

Because blocks are so central to Ruby, you will see them everywhere: in file handling, in database queries, in testing frameworks, and in Rails callbacks. The more comfortable you become with writing and reading blocks, the more natural Ruby code will feel. Practice converting simple loops into each with blocks until the pattern becomes second nature.

Key Takeaways

💡

  • Blocks attach behavior to method calls using do end or brace syntax
  • yield hands control from the method to the attached block
  • block_given? makes blocks optional
  • Enumerable's power comes from methods that accept blocks
  • Chaining select, map, and reduce produces clear data pipelines

Practice Questions

  1. Write a method called twice that yields twice to its block.
  2. What does block_given? return when no block is attached?
  3. Use each to print every animal name in an array of your choice.
  4. Chain select and map to find even numbers and double them.
  5. Explain the difference between writing a block and defining a method.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Ruby Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement