Mike's Blog

Enumeration, what is it good for?

A quick guide to enumeration ruby methods

September 18th 2015


First off, what is enumeration:

An enumeration is a complete, ordered listing of all the items in a collection. The term is commonly used in mathematics and computer science to refer to a listing of all of the elements of a set.


Great, how can we use it?

Well there might be a better way to iterate through an array than the for loops you have been using! Enumerable's biggest advantage is over the for loop is clarity. Using Enumerable's looping "power tools" like any?, All? and others we will define later help make your code read semantically. In addition to your code reading better these methods can get the job done quicker and more efficiently than you thought possible.


Lets take a look at 2 enumeration methods:

  • all? [{ |obj| block } ] → true or false All? asses each element of the collection to the given block. The method returns true if the block never returns false or nil. If the block is not given, Ruby adds an implicit block of{ |obj| obj } which will cause all? to return true when none of the collection members are false or nil.
  • any? [{ |obj| block }] → true or false Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of { |obj| obj } that will cause any? to return true if at least one of the collection members is not false or nil.