让父类的方法访问子类的常量 [英] Have a parent class's method access the subclass's constants

查看:105
本文介绍了让父类的方法访问子类的常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

这篇关于让父类的方法访问子类的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆