ruby - 继承但不与父类(super class)共享,不共享命名空间的变量/常量

标签 ruby variables constants

有没有办法引入一些具有以下三个属性的变量/常量?

a) It inherits a superclass's value when it is not assigned in the own class.

b) It does not inherit other classes's value other than for superclasses's (even if they share the namespace).

c) It does not overwrite the superclasses's value when assigned in the own class.

使用类实例变量,a)不满足。

class A; @foo = :foo end
class B < A; @foo end # => nil  (Does not satisfy (a))
class A; class C; @foo end end # => nil (Satisfies (b))

class B < A; @foo = :bar end
class A; @foo end # => :foo  (Satisfies (c))

使用类变量,c)不满足。

class A; @@foo = :foo end
class B < A; @@foo end # => :foo  (Satisfies (a))
class A; class C; @foo end end # => NameError (Satisfies (b))

class B < A; @@foo = :bar end
class A; @foo end # => :bar  (Does not satisfy (c))

使用常量,b)不满足。

class A; Foo = :foo end
class B < A; Foo end # => :foo  (Satisfies (a))
class A; class C; Foo end end # => :foo (Does not satisfy (b))

class B < A; Foo = :bar end
class A; Foo end # => :foo  (Satisfies (c))

我想要这样的东西:

class A; something = :foo end
class B < A; something end # => :foo  (Satisfies (a))
class A; class C; something end end # => nil or Error (Satisfies (b))

class B < A; something = :bar end
class A; something end # => :foo  (Satisfies (c))

如果不能简单地通过分配和引用变量/常量来完成,那么有没有办法实现具有此属性的访问器方法?

最佳答案

您需要创建您自己的具有所需特定属性的访问器。例如,

module InheritableProperty
  def property
    @property || superclass.property
  end
  def property=(value)
    @property = value
  end
end

class A
  extend InheritableProperty
end
class B < A
  extend InheritableProperty
  class C
    extend InheritableProperty
  end
end

A.property = 1
A.property # => 1
B.property # => 1
B::C.property # error

A.property = 1
B.property = 2
A.property # => 1
B.property # => 2
B::C.property # error

A.property = 1
B.property = 2
B::C.property = 3
A.property # => 1
B.property # => 2
B::C.property # => 3

关于ruby - 继承但不与父类(super class)共享,不共享命名空间的变量/常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14543355/

相关文章:

ruby-on-rails - Rails 导出 csv,包括连接表属性

javascript - 在定义之前使用 javascript 函数

java - 什么数据类型可以存储其他数据类型?

ruby-on-rails - Rails Collection_Select Has_Many 通过

python - "Parseltongue": get Ruby to Speak a bit of Python?

swift - 调用函数后释放类变量

可以/为什么在返回类型中使用 char * 而不是 const char * 会导致崩溃?

c++ - 什么是多级指针?

C++ 声明其大小值来自 const 数组的数组

ruby-on-rails - 具有模型关联的 Rails json 对象