#! ruby -Ks
#-- Enumerable_sum.rb
#-- Enumerable_sum.pi


#undefined method `compact' for #<Range:0x10adf18> (NameError)

module Enumerable
  def sum(ret = nil)
    arr = (block_given? ? self.collect{|i| yield(i)} : self.to_a).compact
    ret ||= arr.shift
    arr.each{|i| ret += i }
    return ret
  end
end

if __FILE__ == $0

  p ([1,2,3,4,nil,5].sum)                            ## 15
  p (["1","2","3","4",nil,"5"].sum)                  ## "12345"
  p (["1","2","3","4",nil,"5"].sum{|i|i.to_i})       ## 15
  p (["1","2","3","4",nil,"5"].sum(100){|i|i.to_i})  ## 115

require "complex"
p [ Complex(1,2), 3.5].sum		##	Complex(4.5, 2)

  module Enumerable
    def inject(n)
      self.each{|x| n = yield(n, x)}
      return n
    end
  end
#  p ([1,2,3,4,nil,5].inject(0){|n,i| n+i })
    #=> nil can't be coerced into Fixnum (TypeError)
  p ([1,2,3,4,nil,5].inject(0){|n,i| n+i.to_i }) # 15
  p (["1","2","3","4",nil,"5"].inject(''){|n,i| n+i.to_s })                  ## "12345"

end

