2

While looking over some Ruby code I noticed methods declared with self. prepended to the method name. For example:

def self.someMethod
  //...
end

What does prepending self. to the method name change about the method?

SundayMonday
  • 19,147
  • 29
  • 100
  • 154

2 Answers2

10

def self.something is a class method, called with:

Class.some_method

def something is an instance method, called with:

class = Class.new
class.some_method

The difference is that one is called on the class itself, the other on an instance of the class.

To define a class method, you can also use the class name, however that will make things more difficult to refactor in the future as the class name may change.

Some sample code:

class Foo
  def self.a
    "a class method"
  end

  def b
    "an instance method"
  end

  def Foo.c
    "another class method"
  end
end

Foo.a # "a class method"
Foo.b # NoMethodError
Foo.c # "another class method"
bar = Foo.new 
bar.a # NoMethodError
bar.b # "an instance method"
bar.c # NoMethodError
Gazler
  • 83,029
  • 18
  • 279
  • 245
  • Interesting. `self` isn't the first keyword I would associate with a class method. – SundayMonday Nov 22 '11 at 22:36
  • 2
    You can also use the class name, I have edited my answer to show this. – Gazler Nov 22 '11 at 22:38
  • Are static variables accessed in a similar manner? Perhaps like this: `self.someVariable`? – SundayMonday Nov 22 '11 at 22:45
  • 1
    @MrMusic, in the ruby world, they are called class variables, they are initialized with the double @@ syntax `@@class_variable` I would recommend creating "getter" and "setter" methods for them. This answer may be of use. http://stackoverflow.com/questions/895747/how-can-rubys-attr-accessor-produce-class-variables-or-class-instance-variables – Gazler Nov 22 '11 at 22:49
  • Ok thanks. I'm still unclear about the significance of `self.` when accessing a variable. – SundayMonday Nov 22 '11 at 23:00
  • self is not associated with class methods. It creates a class method in that context only because self is a class. – Mon ouïe Nov 22 '11 at 23:38
3

The self. causes it to become a class method, rather than an instance method. This is similar to static functions in other languages.

RealCasually
  • 3,593
  • 3
  • 27
  • 34