Monday, 7 June 2021

How Ruby method lookup works?

 When we call a method on an object, Ruby looks for the implementation of that method. 

 It looks in the following places and uses the first implementation it finds:

  1. Methods from the object's singleton class (an unnamed class that only exists for that object)
  2. Methods from prepended modules (Ruby 2.0+ feature)
  3. Methods from the object's class
  4. Methods from included modules
  5. Methods from the class hierarchy (superclass and its ancestors)



class Superclass

  def monk
    puts "rormonk Superclass"
  end 

end


module IncludedModule

  def monk
    puts "rormonk Included module"
    super
  end
  
end


module PrependedModule

  def monk
    puts "rormonk Prepended module"
    super
  end
  
end

module SingletonModule

  def monk
    puts "rormonk Singleton class"
    super
  end

end

class Klass < Superclass
  include IncludedModule
  prepend PrependedModule

  def monk
    puts "rormonk Klass"
    super
  end
  
end


kl = Klass.new kl.extend(SingletonModule) 
kl.monk

Singleton class

Prepended module

Klass

Included module

Superclass


So when I saw first I extend the class and then call the method than obvious it will call that but later I realize if I will not extend that how would I call that 😅

there will be some people like me who could think superclass is mention in every method due to that it is printing like this 😊 so this is for the super is used to maintain the chain so if you will not put super it will not call the other method and it will just return the first method print value.

✌ 

No comments:

Post a Comment