What is a block?
A block is code you hand to a method
Most method calls so far in this series passed plain values as arguments, like access_level("admin", true, false). The hashes course's merge took a block once, without explaining it. A block is a small, unnamed chunk of code passed to a method, which the method can run, even more than once.
3.times { puts "hello" }
# hello
# hello
# hello
{ puts "hello" } is the block, and times calls it three times in a row. puts "hello" didn't need to become a named method first; the block is written where it's used.
Two equivalent syntaxes: {} and do...end
3.times { puts "hi" }
3.times do
puts "hi"
end
Curly braces and do/end both wrap a block. The convention, not a hard rule, is {} for a block that fits on one line and do/end for one that spans several, as in the two examples above.
Blocks can accept a value
[10, 20, 30].each { |n| puts n * 2 }
# 20
# 40
# 60
The |n| between pipes names a variable the block receives each time it runs. each calls the block once per element and hands that element in as n. It's the block version of a method's parameter list, written between pipes instead of parentheses.
Why this matters: one concept, everywhere
Blocks aren't specific to each; times above used one too. This course's each_with_index and the next courses' map and select are built on the same idea: a method receives a block and runs it, handing in whatever value makes sense for that method. Learning to read { |n| ... } here pays off across dozens of methods.
Key takeaways
- A block is code passed to a method, written with
{}ordo/end; both mean the same thing. - Convention:
{}for a one-line block,do/endfor a multi-line one. |n|names a variable the block receives; the calling method decides what to hand in and how many times to run the block.- A method calling the block it was handed is the pattern behind
each,times,map,selectand most of Ruby's iteration methods.
Keep going with lesson 2
Iterating arrays with each
Shows how each runs a block per array element, returns the original array, and supports accumulating outside the block.
A free account also gives you the quizzes, your progress and notes, and the discussion.