Ruby enumerable: each
This course introduces Ruby blocks and the each method. It starts with what a block is, the two syntaxes {} and do...end, and how parameters between pipes receive values. It covers iterating arrays and hashes with each, why each returns the original collection, and how to accumulate results in a variable declared outside the block. It adds each_with_index for element positions, including on hashes. It also explains the precedence difference between {} and do...end, and why block scope makes each preferred over for loops.
What you'll learn
- ✓What a block is and how to write it with {} or do...end
- ✓Iterating arrays and hashes with each and what each returns
- ✓Accumulating results in variables declared outside the block
- ✓Using each_with_index, including destructuring hash pairs
- ✓How {} and do...end differ in precedence
- ✓Why block scope makes each preferred over for loops
What is a block?
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.
Read the full lesson free →Curriculum
7 lessonsWhat is a block?
Defines a block as unnamed code passed to a method, written with {} or do...end, with parameters between pipes.
Iterating arrays with each
Shows how each runs a block per array element, returns the original array, and supports accumulating outside the block.
each_with_index
Uses each_with_index to get each element with its zero-based index, on arrays and on hashes with destructuring.
Iterating hashes with each
Iterates hashes with each using key and value parameters, or one parameter receiving the pair as an array.
Choosing {} or do...end
Explains the style convention for {} and do...end and how their different precedence can attach a block wrongly.
each vs for loops
Compares each with for loops, showing that for leaks variables while a block keeps its own local scope.
Putting it together: a small challenge
Combines a guard clause, accumulation, each_with_index on a hash and do...end in a small report-building challenge.