For example:
class Animal
def make_noise
print NOISE
end
end
class Dog < Animal
NOISE = "bark"
end
d = Dog.new
d.make_noise # I want this to print "bark"
How do I accomplish the above? Currently it says
uninitialized constant Animal::NOISE
I think that you don't really want a constant; I think that you want an instance variable on the class:
class Animal @noise = "whaargarble" class << self attr_accessor :noise end def make_noise puts self.class.noise end end class Dog < Animal @noise = "bark" end a = Animal.new d = Dog.new a.make_noise #=> "whaargarble" d.make_noise #=> "bark" Dog.noise = "WOOF" d.make_noise #=> "WOOF" a.make_noise #=> "whaargarble"
However, if you are sure that you want a constant:
class Animal def make_noise puts self.class::NOISE # or self.class.const_get(:NOISE) end end
one way to do it without class instance variables:
class Animal def make_noise print self.class::NOISE end end class Dog < Animal NOISE = "bark" end d = Dog.new d.make_noise # prints bark
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With