P
Phrogz
Is there an idiom for doing something to the first value as part of an
inject? Or do I need to .map{}.inject{}?
class Array
def sum
inject(0){ |total, entry| total + entry.to_f }
end
def product
inject(1){ |total, entry| total * entry.to_f }
end
def running_difference
inject{ |total, entry| total - entry.to_f }
end
def running_divide
inject{ |total, entry| total / entry.to_f }
end
end
a1 = [5,4,3,2,1]
p a1.sum
#=> 15.0
p a1.product
#=> 120.0
p a1.running_difference
#=> -5.0
p a1.running_divide
#=> 0.208333333333333
a2 = ["5","4","3","2","1"]
p a2.sum
#=> 15.0
p a2.product
#=> 120.0
p a2.running_difference
#=> tmp.rb:9:in `running_difference': undefined method `-' for
"5":String (NoMethodError)
#=> from tmp.rb:36:in `inject'
#=> from tmp.rb:9:in `running_difference'
#=> from tmp.rb:31
inject? Or do I need to .map{}.inject{}?
class Array
def sum
inject(0){ |total, entry| total + entry.to_f }
end
def product
inject(1){ |total, entry| total * entry.to_f }
end
def running_difference
inject{ |total, entry| total - entry.to_f }
end
def running_divide
inject{ |total, entry| total / entry.to_f }
end
end
a1 = [5,4,3,2,1]
p a1.sum
#=> 15.0
p a1.product
#=> 120.0
p a1.running_difference
#=> -5.0
p a1.running_divide
#=> 0.208333333333333
a2 = ["5","4","3","2","1"]
p a2.sum
#=> 15.0
p a2.product
#=> 120.0
p a2.running_difference
#=> tmp.rb:9:in `running_difference': undefined method `-' for
"5":String (NoMethodError)
#=> from tmp.rb:36:in `inject'
#=> from tmp.rb:9:in `running_difference'
#=> from tmp.rb:31