Ruby Enumerable Methods

By Philip Riley and Matt DuBois

Ruby has a number of built-in searching and sorting methods that can be used on various types of collection classes, including arrays, hashes, strings and ranges of numbers. These enumerable methods are powerful tools to collect only the elements that pass through blocks of code that you specify. In order to use these enumerable methods, the collection class must have a built in ".each" method. The methods then work off the ".each" method. Enumerables are typically used on arrays and hashes, but it's important to remember they can also work on strings or ranges of numbers. Below is a table of some of the most useful and commonly used enumerable methods. More methods can be found in Ruby Docs.

Method Name Description Example Output
.map/collect Returns a new array with the results of each item passed through the given block. [1,2,3,4].map {|num| num * 2} => [2,4,6,8]
.any? Returns true/false by checking if any element meets criteria in given block. [1,2,3,4].any? {|num| num % 5 == 0} => false
.all? Returns true/false by checking if all elements meet criteria in given block. [1,2,3,4].all? {|num| num < 10} => true
.each_with_index Calls a block with two elements, one for each element and one for each index. [1,2,3,4].each_with_index {|num, index| puts num * index} => 0,2,6,12
.include? Returns true/false to answer whether enumerable contains object within parentheses. [1,2,3,4].include?(2) => true
.inject Each element is passed an accumulator value and element. Each element is passed through block, result is stored in accumulator value. [1,2,3,4].inject {|sum, num| sum + num} => 10