From: gotoken@... (GOTO Kentaro) Date: 2001-01-08T06:19:42+09:00 Subject: [ruby-talk:8784] Re: No :<, :>, etc. methods for Array In message "[ruby-talk:8782] Re: No :<, :>, etc. methods for Array" on 01/01/08, "Brian F. Feldman" writes: >I know you can define sum in terms of inject, but what is the point of >having inject if people are just going to use it to create sum? Well, I think we sometimes need to write something: def product @array.inject(1){|p,i| p *= i} end def sum inject(element_type.induced_from(0)){|n,i| n.add!(i)} end def average_score @profile.inject(0){|s,i| s += i.score}/@size end or def pipeline @process.inject(Product.new){|r,p| p.call(r)} end So, inject seems to be not only theoretical. Furthermore, I don't need Array#sum so often. On the other hand, when I need sum I need often also average, variance or square_error{|x| model(x)}. For Enumerable, maybe a module `Statistics' is more useful. Btw, I think that sum's argument for the empty case is convenient, e.g.: def sum(if_empty = 0) # Is the integer zero suitable? total = if_empty self.each {|x| total += x} total end -- Gotoken