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
To access a class method inside a instance method, do the following:
self.class.default_make
Here is an alternative solution for your problem:
class Truck
attr_accessor :make, :year
def self.default_make
"Toyota"
end
def make
@make || self.class.default_make
end
def initialize(make=nil, year=nil)
self.year, self.make = year, make
end
end
Now let's use our class:
t = Truck.new("Honda", 2000)
t.make
# => "Honda"
t.year
# => "2000"
t = Truck.new
t.make
# => "Toyota"
t.year
# => nil