Florian Gilcher
2/18/2009 3:42:00 PM
On Feb 18, 2009, at 4:36 PM, Valentino Lun wrote:
>
> [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?
Enumerable is a Module, not a Class. It can be mixed into other
classes, so the Class gains the Methods of the module. Arrays uses
Enumerable instead of implementing #inject on its own, so they respond
to Enumerables #inject.
As a short presentation, i redefine Enumerable#inspect to do something
different (never try this at home!):
===
module Enumerable
def inject
puts "hey"
end
end
[].inject #=> puts "hey" now
===
Regards,
Florian Gilcher
--
Florian Gilcher
smtp: flo@andersground.net
jabber: Skade@jabber.ccc.de
gpg: 533148E2