blob: 4de520f4edbcbfa9ad04b9a6d678de8d4adc9e7b (
plain) (
tree)
|
|
require File.dirname(__FILE__) + '/enumerable/injections'
module Enumerable #:nodoc:
# Collect an enumerable into sets, grouped by the result of a block. Useful,
# for example, for grouping records by date.
#
# e.g.
#
# latest_transcripts.group_by(&:day).each do |day, transcripts|
# p "#{day} -> #{transcripts.map(&:class) * ', '}"
# end
# "2006-03-01 -> Transcript"
# "2006-02-28 -> Transcript"
# "2006-02-27 -> Transcript, Transcript"
# "2006-02-26 -> Transcript, Transcript"
# "2006-02-25 -> Transcript"
# "2006-02-24 -> Transcript, Transcript"
# "2006-02-23 -> Transcript"
def group_by
inject({}) do |groups, element|
(groups[yield(element)] ||= []) << element
groups
end
end
# Calculates a sum from the elements. Examples:
#
# payments.sum { |p| p.price * p.tax_rate }
# payments.sum(&:price)
#
# This is instead of payments.inject(0) { |sum, p| sum + p.price }
def sum
inject(0) { |sum, element| sum + yield(element) }
end
end
|