sort_by
Like sort, 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 than sort when the block is expensive
to compute.
zip(*others)
Returns an array of tuples, built up from one element each from self and others:
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]
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.
Pages:
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72