Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have a parent class's method access the subclass's constants

Tags:

ruby

constants

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
like image 887
Tim Avatar asked Jan 26 '12 06:01

Tim


2 Answers

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 
like image 108
Phrogz Avatar answered Sep 23 '22 01:09

Phrogz


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 
like image 31
Patrick Klingemann Avatar answered Sep 19 '22 01:09

Patrick Klingemann