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

(Tuis.) #1

38 | Chapter 1: Foundational Techniques


reject
Returns an array of all items in the collection for which the block evaluates to
false.


grep(x)
Returns an array of all items in the collection for which x=== itemistrue. This
usage is equivalent toselect{|item| x === item}.


Transformers


These methods transform a collection into another collection by one of several rules.


map,collect
Returns an array consisting of the result of the given block being applied to each
element in turn.


partition
Equivalent to[select(&block), reject(&block)].


sort
Returns a new array of the elements in this collection, sorted by either the given
block (treated as the<=> method) or the elements’ own<=> method.


sort_by
Likesort, but yields to the given block to obtain the values on which to sort. As
array comparison is performed in element order, you can sort on multiple fields
with person.sort_by{|p| [p.city, p.name]}. Internally, sort_by performs a
Schwartzian transform, so it is more efficient thansortwhen the block is expen-
sive to compute.


zip(*others)
Returns an array of tuples, built up from one element each fromself andothers:
puts [1,2,3].zip([4,5,6],[7,8,9]).inspect


>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]


When the collections are all of the same size,zip(*others)is equivalent to
([self]+others).transpose:
puts [[1,2,3],[4,5,6],[7,8,9]].transpose.inspect


>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]


When a block is given, it is executed once for each item in the resulting array:
[1,2,3].zip([4,5,6],[7,8,9]) {|x| puts x.inspect}


>> [1, 4, 7]


>> [2, 5, 8]


>> [3, 6, 9]

Free download pdf