Timothy Goddard
10/2/2006 7:29:00 AM
The base level in Ruby runs in the context of an instance of Object.
When you add base level methods you're actually adding those methods to
the eigenclass of the main object. The main object in essence is an
instance of its eigenclass and the eigenclass is a subclass of the
Object class. You can do this with any Ruby object (except Fixnums,
which is an annoying inconsistency):
irb(main):010:0> a = "Frog"
=> "Frog"
irb(main):011:0> def a.double
irb(main):012:1> self * 2
irb(main):013:1> end
=> nil
irb(main):014:0> a.double
=> "FrogFrog"
irb(main):015:0> b = "Camel"
=> "Camel"
irb(main):016:0> b.double
NoMethodError: undefined method `double' for "Camel":String
from (irb):16
from :0
Note that the original String class isn't affected - the method has
been added to the eigenclass of object a.
MonkeeSage wrote:
> Trans wrote:
> > Yes, but so is everything.
>
> Hmmm...I'm not the sharpest tool in the shed, but I don't think that is
> correct. There are first-order objects like classes and modules.
> Normally #included gets the class or module object itself, not an
> instance. At least that's how I've always thought it worked.
>
> module Test
> def self.included(base)
> p base.instance_of?(C) # => false
> base.module_eval { # <- extends the actual class, not an instance
> def m
> puts 'Howdy do'
> end
> }
> end
> end
> class C
> include Test
> end
> C.new.m
>
> Regards,
> Jordan