I want to get the class instance by its name, such as I input the
category:
Base
it should find the class whose name is ‘Base_tax’, then create a
instance,
and I can use the instance, such as i can invoke the method:
tax.getRate
I try almost every methods, however, no can implement. Some methods just
create a class without methods, that is not what i want.
I want to get the class instance by its name, such as I input the
category:
Base
it should find the class whose name is ‘Base_tax’, then create a
instance,
and I can use the instance, such as i can invoke the method:
tax.getRate
i’m a bit confused by a few things, including whether
“tax_class_name”, “tax_class”, and “tax” represent different ways of
trying the same thing or if they’re different, and where you want #getRate defined - but maybe something like this helps?
class TaxFactory
def initialize(category)
tax = Object::const_get("#{category}Tax").new
self.get_rate(tax)
end
def get_rate(tax)
puts “#{tax.class} rate is #{tax.rate}%”
end
end
class BaseTax
attr_reader :rate
def initialize @rate = 5
end
end
class LuxuryTax
attr_reader :rate
def initialize @rate = 12
end
end
base = TaxFactory.new(“Base”)
lux = TaxFactory.new(“Luxury”)
i’m a bit confused by a few things, including whether
“tax_class_name”, “tax_class”, and “tax” represent different ways of
trying the same thing or if they’re different, and where you want #getRate defined - but maybe something like this helps?
class TaxFactory
def initialize(category)
tax = Object::const_get("#{category}Tax").new
self.get_rate(tax)
end
def get_rate(tax)
puts “#{tax.class} rate is #{tax.rate}%”
end
end
class BaseTax
attr_reader :rate
def initialize @rate = 5
end
end
class LuxuryTax
attr_reader :rate
def initialize @rate = 12
end
end
base = TaxFactory.new(“Base”)
lux = TaxFactory.new(“Luxury”)
=> BaseTax rate is 5%
=> LuxuryTax rate is 12%
j
Thanks, yes, what i want to write is like your code. But when i copy
your code, run on my computer, there is an error: