OneZero OneZero - 7 months ago 9
Ruby Question

What does self. mean in a class method?

In Programming Ruby, I saw a class method is defined as

class File
def self.my_open(*args)
#...
end
end


What does the prefix "self." mean here?

Answer

Using syntax def receiver.method you can define methods on a specific objects.

class Dog
  def bark
    puts 'woof'
  end
end

normal_dog = Dog.new
angry_dog = Dog.new


def angry_dog.bite
  puts "yum"
end


normal_dog.class # => Dog
angry_dog.class # => Dog

angry_dog.bite # >> yum
normal_dog.bite # ~> -:15:in `<main>': undefined method `bite' for #<Dog:0x007f9a93064cf0> (NoMethodError)

Note that even though dogs are of the same class Dog, one of them has a unique method that another dog doesn't.

The same thing with classes. Inside of class definition, self points to that class. This is critical to understanding.

class Foo
  self # => Foo
end

Now let's look at these two classes:

class Foo
  def self.hello
    "hello from Foo"
  end
end

class Bar
end

Foo.class # => Class
Bar.class # => Class


Foo.hello # => "hello from Foo"
Bar.hello # ~> -:15:in `<main>': undefined method `hello' for Bar:Class (NoMethodError)

Even though both Foo and Bar are both instances (objects) of class Class, one of has a method which another doesn't. The same thing.

If you omit the self in method definition, then it becomes instance method and it will be available on instances of a class rather than on the class itself. See the Dog#bark definition in the first snippet.

For closing, here's a couple more methods of how you can define a class instance method:

class Foo
  def self.hello1
    "hello1"
  end

  def Foo.hello2
    "hello2"
  end
end

def Foo.hello3
  "hello3"
end


Foo.hello1 # => "hello1"
Foo.hello2 # => "hello2"
Foo.hello3 # => "hello3"
Comments