从父母的班级中获取孩子的常数

时间:2018-02-15 22:23:33

标签: ruby

如果子进程从父进程继承,它也会继承parent方法。

那么继承方法怎么能够访问孩子的常量呢?

示例 -

BehaviorSubject

没有继承的方法运行"内部"孩子班?

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

不,它没有。当您致电Child.new.my_method时,它会在FOO及以上查找Parent常量。

我不会质疑你的方法,只是为你提供一个做你想做的事的方法:

class Parent
  def self.inherited(other)
    other.define_singleton_method(:my_method) do
      puts "Value of FOO is #{other.const_get(:FOO)}"
    end
  end
end

现在,无论何时从Parent继承,继承的钩子都会在子类上定义方法my_method。请注意,inherited方法中块的范围仍然是Parent的类级别范围。这就是为什么我直接引用子类(other)来获取常量的原因。 解决这个问题的方法是使用other.instance_exec { ... }

更新

@maxpleaner指出(通过@CarySwoveland提供的解释)您还可以通过self检索该类,然后从中检索该常量。

即,只做

class Parent
  def my_method
    puts "Values of FOO is #{self.class.const_get(:FOO)}"
  end
end

这是有效的,因为在致电child = Child.new; child.my_method时,selfmy_method的值将为childchild的类显然是Child,它知道常量FOO

答案 1 :(得分:1)

不确定问题是什么,但是如果您需要从子对象访问常量。为什么不使用子对象。

物体之美在于你使用你需要的最具体的物体。

相关问题