Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Functional Programming | 39

Aggregators


These methods aggregate or summarize the data.


inject(initial)
Folds an operation across a collection. Initially, yields an accumulator (initial
provides the first value) and the first object to the block. The return value is used
as the accumulator for the next iteration. Collection sum is often defined thus:
module Enumerable
def sum
inject(0){|total, x| total + x}
end
end
If no initial value is given, the first iteration yields the first two items.


max
Returns the maximum value in the collection, as determined by the same logic as
thesort method.


min
Likemax, but returns the minimum value in the collection.


Other


each_with_index
Likeeach, but also yields the 0-based index of each element.


entries, to_a
Pushes each element in turn onto an array, then returns the array.


TheEnumerablemethods are fun, and you can usually find a customized method to
do exactly what you are looking for, no matter how obscure. If these methods fail
you, visit Ruby Facets (http://facets.rubyforge.org) for some inspiration.


Enumerator


Ruby has yet another little-known trick up its sleeve, and that isEnumeratorfrom the
standard library. (As it is in the standard library and not the core language, you must
require "enumerator" to use it.)


Enumerableprovides many iterators that can be used on any enumerable object, but it
has one limitation: all of the iterators are based on theeachinstance method. If you
want to use some iterator other thaneachas the basis formap,inject, or any of the
other functions inEnumerable, you can useEnumerator as a bridge.

Free download pdf