patternrubyCritical
Ruby: Calling class method from instance
Viewed 0 times
instancefromclasscallingmethodruby
Problem
In Ruby, how do you call a class method from one of that class's instances? Say I have
the line
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
endthe line
Truck.default_make retrieves the default. But is there a way of saying this without mentioning Truck? It seems like there should be.Solution
Rather than referring to the literal name of the class, inside an instance method you can just call
Outputs:
Class method: Foo
Instance method: Foo
self.class.whatever.class Foo
def self.some_class_method
puts self
end
def some_instance_method
self.class.some_class_method
end
end
print "Class method: "
Foo.some_class_method
print "Instance method: "
Foo.new.some_instance_methodOutputs:
Class method: Foo
Instance method: Foo
Code Snippets
class Foo
def self.some_class_method
puts self
end
def some_instance_method
self.class.some_class_method
end
end
print "Class method: "
Foo.some_class_method
print "Instance method: "
Foo.new.some_instance_methodContext
Stack Overflow Q#2527830, score: 656
Revisions (0)
No revisions yet.