December 14, 2014

Ruby – Enumerables

In ruby “Enumerables” is actually name of module. A module is essentially a collection of constants and methods.


You can find all my latest posts on medium.

The Enumerables module contains a collection of methods that are specifically designed to iterate through a collection of objects (e.g. elements in an array), and run some ruby code against each object.

for this reason, the enumerables methods comes built into the array class.

One commonly used enumerable is the “map”, this method lets you generate a new a new array from an existing class, using the block-form syntax:

irb(main):241:0* arr = [11,12,13,14]
=> [11, 12, 13, 14]
irb(main):242:0> {|value| value - 2 }
=> [9, 10, 11, 12]

There’s also a “reduce” that you can use to sum up the numbers in an array:

irb(main):251:0> [1,2,3].reduce(0) {|sum, v| sum + v}
=> 6

The zero parameter for the “reduce” method is the initial value that the “sum” variable takes, e.g.:

irb(main):252:0> [1,2,3].reduce(4) {|sum, v| sum + v}
=> 10

The enumerable method also has a “select” and “sort” methods:

irb(main):276:0> [100,12,43,5,58,150].select {|n| n.even?}
=> [100, 12, 58, 150]
irb(main):277:0> [100,12,43,5,58,150] {|n| n.even?}
=> [12, 58, 100, 150]

As you can see the “select” method lets you intelligently select a subset of an array, based on elements meeting a certain criteria. E.g. if “n.even?” is true, then element get’s selected.

See also: