juniorRuby
What is an array block iterator like #each, and how does it differ from a standard loop?
Updated May 17, 2026
Short answer
#each is an internal iterator that accepts a block and yields each element sequentially, maintaining clean block scoping. Standard loops (for) are external iterators that leak variable scope.
Deep explanation
The #each method is idiomatic in Ruby, leveraging closures. It isolates scope; any variable declared inside the block parameter is discarded once the block terminates. The for in loop, conversely, is syntax sugar over #each, but it does not create a new lexical scope. Any iterator variable declared inside a for loop remains accessible outside the loop, causing accidental scope pollution.
Real-world example
Processing collections of records from database queries safely without overwriting local loop flags or transient indexing identifiers.
Common mistakes
- Using a `for` loop in Ruby assuming it functions identically to scoped loop structures in block-scoped languages like JavaScript or Java.
Follow-up questions
- What does `#each` return after completion?
- What module provides collection methods like select, reject, and map?