Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self vs class name for class methods in inheritance

In this code:

class Dog
  def self.bark
    print "woof"
  end
end

class Little_dog < Dog
end

Little_dog.bark

the method is inherited from a generalised class that references self. But the next patch of code:

class Dog
  def Dog.bark
    print "woof"
  end
end

class Little_dog < Dog
end

Little_dog.bark

also works. I was expecting it to give me an error, but it didn't.

How does self refer to the class method under class inheritance? Why does the little_dog class have a class method bark in the second example when I only defined it as a class method of Dog?

like image 691
Zach Smith Avatar asked Feb 06 '26 01:02

Zach Smith


2 Answers

self is widely used in Ruby Metaprogramming.

From Metaprogramming Ruby book:

Every line of Ruby code is executed inside an object—the so–called current object. The current object is also known as self, because you can access it with the self keyword.

Only one object can take the role of self at a given time, but no object holds that role for a long time. In particular, when you call a method, the receiver becomes self. From that moment on, all instance variables are instance variables of self, and all methods called without an explicit receiver are called on self. As soon as your code explicitly calls a method on some other object, that other object becomes self.

So, in code:

class Dog
  # self represents the class object i.e: Dog. Which is an instance of Class.
  # `bark` will be treated as class method
  def self.bark 
    print "woof"
  end
end

can also be written as:

class Dog
  # Dog is an instance of Class.
  # `bark` will be treated as class method
  def Dog.bark 
    print "woof"
  end
end

Inheritance allows a subclass to use features of its parent class. That's why you can access bark method in Little_dog class since it is inherited Dog class:

class Little_dog < Dog
  # has `bark` as a class method because of Dog
end

Ruby style guide tip: In Ruby it's considered as a best practice to use CamelCase convention for naming classes and modules.

like image 121
Surya Avatar answered Feb 08 '26 04:02

Surya


When you're defining class method it actually doesn't matter if you use

Dog.bark

or

self.bark

Both method defines class method which will be inherited by subclasses.

Only difference is when you will be changing name of class Dog to something else, like BigDog - when you use Dog.bark it obviously needs to be changed to BigDog.bark.

When using self method definition, self.bark will still work.

like image 22
Esse Avatar answered Feb 08 '26 05:02

Esse