← Back to Ruby Course | Chapter 8: Blocks, Procs & Lambdas | Lesson 1 of 6

Block Basics (Review)

This review revisits blocks: little pieces of code passed to a method to be run later. It is like handing over a small set of instructions with your request.

In this page:

  1. Block Basics (Review)
Syntax
ruby
method_name { |param| expression }

method_name do |param|
  # body
end

Block Basics (Review)

A block is the code attached to a method call with { } or do...end, and it isn't an object by itself -- it only exists as part of that specific call, invoked via yield.

This tutorial revisits blocks specifically to contrast them with Proc and Lambda, which turn similar logic into a reusable, storable object. Understanding this distinction is key to picking the right tool for a given situation.

Note: A bare block can't be stored in a variable or passed around on its own -- for that, you need a Proc or Lambda.

Example: Block Basics (Review)

markup
def run_twice
  yield
  yield
end

run_twice { puts "Running from a block" }
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to store a block in a variable like x = { puts 1 }, which is not valid, since a block is not an object.
  2. Confusing a block with a hash, since both use braces.
  3. Passing a block to a method that does not use it, so it is silently ignored.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.