In Ruby, how do you call a class method from one of that class's instances? Say I have
class Truck
def self.default_make
# Class method.
"mac"
end
def initialize
# Instance method.
Truck.default_make # gets the default via the class's method.
# But: I wish to avoid mentioning Truck. Seems I'm repeating myself.
end
end
the line Truck.default_make
retrieves the default. But is there a way of saying this without mentioning Truck
? It seems like there should be.
To access a class method inside a instance method, do the following:
Here is an alternative solution for your problem:
Now let's use our class:
You're doing it the right way. Class methods (similar to 'static' methods in C++ or Java) aren't part of the instance, so they have to be referenced directly.
On that note, in your example you'd be better served making 'default_make' a regular method:
Class methods are more useful for utility-type functions that use the class. For example:
Using
self.class.blah
is NOT the same as usingClassName.blah
when it comes to inheritance.