enumerable.rb 3.7 KB
Newer Older
1 2
require 'active_support/ordered_hash'

3
module Enumerable
4 5 6
  # Ruby 1.8.7 introduces group_by, but the result isn't ordered. Override it.
  remove_method(:group_by) if [].respond_to?(:group_by) && RUBY_VERSION < '1.9'

7 8 9
  # Collect an enumerable into sets, grouped by the result of a block. Useful,
  # for example, for grouping records by date.
  #
P
Pratik Naik 已提交
10
  # Example:
11 12
  #
  #   latest_transcripts.group_by(&:day).each do |day, transcripts| 
13
  #     p "#{day} -> #{transcripts.map(&:class).join(', ')}"
14 15 16 17 18 19 20 21 22
  #   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
23 24 25 26 27 28 29 30 31 32
    assoc = ActiveSupport::OrderedHash.new

    each do |element|
      key = yield(element)

      if assoc.has_key?(key)
        assoc[key] << element
      else
        assoc[key] = [element]
      end
33
    end
34 35

    assoc
36
  end unless [].respond_to?(:group_by)
37 38 39

  # Calculates a sum from the elements. Examples:
  #
40 41
  #  payments.sum { |p| p.price * p.tax_rate }
  #  payments.sum(&:price)
42
  #
43
  # The latter is a shortcut for:
P
Pratik Naik 已提交
44
  #
P
Pratik Naik 已提交
45
  #  payments.inject(0) { |sum, p| sum + p.price }
46
  #
47
  # It can also calculate the sum without the use of a block.
P
Pratik Naik 已提交
48
  #
49 50 51
  #  [5, 15, 10].sum # => 30
  #  ["foo", "bar"].sum # => "foobar"
  #  [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
52
  #
53
  # The default sum of an empty list is zero. You can override this default:
54
  #
55
  #  [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
56 57
  #
  def sum(identity = 0, &block)
58
    if block_given?
59
      map(&block).sum(identity)
60
    else
61
      inject { |sum, element| sum + element } || identity
62
    end
63
  end
64

65 66 67 68
  # Iterates over a collection, passing the current element *and* the
  # +memo+ to the block. Handy for building up hashes or
  # reducing collections down to one object. Examples:
  #
69 70
  #   %w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase }
  #   # => {'foo' => 'FOO', 'bar' => 'BAR'}
71 72 73 74 75 76 77 78
  #
  # *Note* that you can't use immutable objects like numbers, true or false as
  # the memo. You would think the following returns 120, but since the memo is
  # never changed, it does not.
  #
  #   (1..5).each_with_object(1) { |value, memo| memo *= value } # => 1
  #
  def each_with_object(memo, &block)
79 80
    each do |element|
      block.call(element, memo)
81
    end
82
    memo
83 84
  end unless [].respond_to?(:each_with_object)

N
Nicholas Seckar 已提交
85
  # Convert an enumerable to a hash. Examples:
86
  #
N
Nicholas Seckar 已提交
87 88 89 90 91 92 93 94 95 96 97
  #   people.index_by(&:login)
  #     => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
  #   people.index_by { |person| "#{person.first_name} #{person.last_name}" }
  #     => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
  # 
  def index_by
    inject({}) do |accum, elem|
      accum[yield(elem)] = elem
      accum
    end
  end
98 99
  
  # Returns true if the collection has more than 1 element. Functionally equivalent to collection.size > 1.
100 101 102
  # Works with a block too ala any?, so people.many? { |p| p.age > 26 } # => returns true if more than 1 person is over 26.
  def many?(&block)
    size = block_given? ? select(&block).size : self.size
103 104
    size > 1
  end
105 106 107 108 109
  
  # The negative of the Enumerable#include?. Returns true if the collection does not include the object.
  def exclude?(object)
    !include?(object)
  end
110
end
111 112

class Range #:nodoc:
113 114
  # Optimize range sum to use arithmetic progression if a block is not given and
  # we have a range of numeric values.
115
  def sum(identity = 0)
116
    return super if block_given? || !(first.instance_of?(Integer) && last.instance_of?(Integer))
117 118 119 120
    actual_last = exclude_end? ? (last - 1) : last
    (actual_last - first + 1) * (actual_last + first) / 2
  end
end