Ruby enumerator

Enumerable module in Ruby

If you’ve written any script or code in Ruby, you’ve definitely used the Enumerable module.

The Enumerable module extends the functionality of collections. When I say collection think arrays and hashes. The Enumerable module enables you to call methods on each object of a collection using the #each method.

It’s one of the reasons why I love Ruby – clean, expressive, and generally makes life better.

# Give me an example
This will better contextualize what I mean. You can perform individual actions on each object in a collection using the #each method.

Here’s a popular Enumerable method – map. The map method modifies each member in a block and returns a the modified collection:

# Creates array
example = %w(car bike truck)
# Prints new array that’s been modified by Enumerable’s map method
mapped_example = example.map { |v| v.upcase } 
# Here’s the new array
Puts mapped_example
 => ["CAR", "BIKE", "TRUCK"]

Viola. Ruby’s Enumerable module.

No Comments

Post a Comment