Intern Track Roadmap

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
Free preview · Lesson 1 2 min read

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 lessons
Type to start searching...