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:
Syntax
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)
def run_twice
yield
yield
end
run_twice { puts "Running from a block" }
Login to try C/C++/Java/PHP code in the editor
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
- Trying to store a block in a variable like
x = { puts 1 }, which is not valid, since a block is not an object. - Confusing a block with a hash, since both use braces.
- 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: