From: Brian Candler Date: 2009-02-19T18:13:29+09:00 Subject: Re: Dummy question about method in class Valentino Lun wrote: > I have a dummy question. > > [1,2,3,4,5].inject { |sum,n| sum+n } > The inject method in this case is to calculate the sum of array. > > I searched the RDoc. Why the inject method is belongs to Enumerable > Class, but not Array Class? The Enumerable module can be shared by many classes. Any class which implements its own 'each' method can mixin Enumerable and gain a whole load of functionality. For example: class Fib include Enumerable def initialize(a,b,count) @a, @b, @count = a, b, count end def each @count.times do yield @a @a, @b = @b, @a+@b end end end p Fib.new(1,1,10).inspect p Fib.new(1,1,10).max p Fib.new(1,1,10).inject(0) { |sum,n| sum+n } -- Posted via http://www.ruby-forum.com/.