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?
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?
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
The self. causes it to become a class method, rather than an instance method. This is similar to static functions in other languages.