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.
Rather than referring to the literal name of the class, inside an instance method you can just call
self.class.whatever
.Outputs:
Similar your question, you could use:
If you have access to the delegate method you can do this:
Alternatively, and probably cleaner if you have more then a method or two you want to delegate to class & instance:
A word of caution:
Don't just randomly
delegate
everything that doesn't change state to class and instance because you'll start running into strange name clash issues. Do this sparingly and only after you checked nothing else is squashed.One more:
Here's an approach on how you might implement a
_class
method that works asself.class
for this situation. Note: Do not use this in production code, this is for interest-sake :)From: Can you eval code in the context of a caller in Ruby? and also http://rubychallenger.blogspot.com.au/2011/07/caller-binding.html
Maybe the right answer is to submit a patch for Ruby :)