Class, Module, their eigenclasses, and method lookup
Asked Answered
H

3

5

Let's open class Module and add a method to it:

class Module  
  def foo  
    puts "phew"  
  end  
end

I can call this method by doing this,

Class.foo

which is understandable because class of Class is Class, whose superclass is Module. so it can call instance methods defined in Module.

relation between classes and modules

Now, the method bar below is defined on Module's eigenclass:

class Module  
   def self.bar  
     puts "bar"  
   end  
end

but now

Class.bar 

also works.

Can someone explain me how Class can access methods in Module's eigenclass?


I think I got it now. Method look up doesn't work the way I explained before. when I do Class.foo, the method is searched in Class's eigenclass and then it's superclass which is Module's eigenclass all the way upto BasicObject's eigenclass at which point it turns upon itself (like a serpent eating it's own tail) to look for method in Class (as Class is the superclass of BasicObject's eigenclass) and then to it's superclass Module, where it finds the method.

Similarly, when I do Class.bar, method is searched in Class's eigenclass and then in Module's eigenclass where it finds it.

When I do

class Class   
  def check  
    puts "class instance method"  
  end
end   

and

class Module   
  def self.check    
    puts "modules eigenclass method"     
  end    
  def check    
    puts "module instance method"   
  end     
end

guess wot is the output when I do:

Class.check 

This is my current understanding: current understanding

Henke answered 18/3, 2013 at 11:25 Comment(1)
Related discussion I found helpful: #13269771Trypsin
C
0

I recently wrote a pretty extensive tutorial, including new Ruby 2.0 behavior.

Note: the term used in Ruby is singleton_class, not eigenclass.

Contrite answered 13/4, 2013 at 19:44 Comment(1)
Link at that url is deadTrypsin
O
1

There is a fairly comprehensive overview of Ruby's method lookup behaviour when Eigenclasses are involved in this blog post by Andrea Singh. Notably, the "Eigenclasses and Class Inheritance" section near the very end contains a useful lookup diagram that should address your questions.

Oneself answered 13/4, 2013 at 19:39 Comment(1)
Is this current as of Ruby 2.2?Trypsin
C
0

I recently wrote a pretty extensive tutorial, including new Ruby 2.0 behavior.

Note: the term used in Ruby is singleton_class, not eigenclass.

Contrite answered 13/4, 2013 at 19:44 Comment(1)
Link at that url is deadTrypsin
S
0

I recently wrote a tutorial about the eigenclass in Ruby:

Understanding the eigenclass in less than 5 minutes

Sub answered 16/1, 2019 at 10:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.