Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Changeset 4599

Show
Ignore:
Timestamp:
07/09/06 20:48:31 (2 years ago)
Author:
bitsweat
Message:

Optional identity for Enumerable#sum defaults to zero. Closes #5657.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/activesupport/CHANGELOG

    r4555 r4599  
    11*SVN* 
     2 
     3* Optional identity for Enumerable#sum defaults to zero. #5657 [gensym@mac.com] 
    24 
    35* HashWithIndifferentAccess shouldn't confuse false and nil. #5601 [shugo@ruby-lang.org] 
  • trunk/activesupport/lib/active_support/core_ext/enumerable.rb

    r4495 r4599  
    3131  # Also calculates sums without the use of a block: 
    3232  #   [5, 15, 10].sum # => 30 
    33   def sum(&block) 
     33  # 
     34  # The default identity (sum of an empty list) is zero.  
     35  # However, you can override this default: 
     36  # 
     37  # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0) 
     38  # 
     39  def sum(identity = 0, &block) 
     40    return identity unless size > 0 
    3441    if block_given? 
    3542      map(&block).sum 
  • trunk/activesupport/test/core_ext/enumerable_test.rb

    r4595 r4599  
    4545    assert_equal 60, payments.sum { |p| p.price.to_i * 2 } 
    4646  end 
    47  
     47   
     48  def test_empty_sums 
     49    assert_equal 0, [].sum 
     50    assert_equal 0, [].sum { |i| i } 
     51    assert_equal Payment.new(0), [].sum(Payment.new(0)) 
     52  end 
     53   
    4854  def test_index_by 
    4955    payments = [ Payment.new(5), Payment.new(15), Payment.new(10) ]