Prev | Current Page 61 | Next

Brad Ediger

"Advanced Rails"


max
Returns the maximum value in the collection, as determined by the same logic as
the sort method.
min
Like max, but returns the minimum value in the collection.
Other
each_with_index
Like each, 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.
The Enumerable methods 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 is Enumerator from the
standard library. (As it is in the standard library and not the core language, you must
require "enumerator" to use it.)
Enumerable provides many iterators that can be used on any enumerable object, but it
has one limitation: all of the iterators are based on the each instance method. If you
want to use some iterator other than each as the basis for map, inject, or any of the
other functions in Enumerable, you can use Enumerator as a bridge.
40 | Chapter 1: Foundational Techniques
The signature of Enumerator.new is Enumerator.new(obj, method, *args), where obj is
the object to enumerate over, method is the base iterator, and args are any arguments
that the iterator receives. As an example, you could write a map_with_index function
(a version of map that passes the object and its index to the given block) with the following
code:
require "enumerator"
module Enumerable
def map_with_index &b
enum_for(:each_with_index).


Pages:
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73