【发布时间】:2015-09-12 01:15:15
【问题描述】:
我在一个特定的类中有大量不同的方法,它们都计算唯一的实例变量。我一直在使用attr_reader 毫无问题地访问这些,但现在我有几十个,想知道是否有一种首选/雄辩的方式来访问所有这些实例变量——不仅仅是一个解决方案,而是一个普遍的接受的首选方法/风格。
我看到过关于类级别变量的类似问题,但这是我想避免的。也许我可以用一个模块来做到这一点,但我认为那些是为了存储成堆的常量?但也许这是我在常规类继承中缺少的东西?继承self?
如果您将这些实例变量想象成数学常数(pi、欧拉等),它们都会添加一个数字(取决于用户输入)。我知道类和方法做一件事,而 Stack 类和方法肯定做一件事 - 它们只是存储许多其他类和方法所需的数据片段。
我正在使用的代码示例:
class Stack
attr_reader :pi, :euler # ... and dozens more of these
def initialize
@pi = 3.14 + 8
@euler = 0.577 + 8
# dozens more assignements here
end
end
class Overflow
def show
a = Stack.new
p a.pi # attr_reader works fine here
end
end
class AnotherClass
def some_method_that_needs_all_variables_in_Stack
# Do I need to create another instance of the
# Stack class like I did in Overflow?
# or should AnotherClass somehow inherit all the instance variables?
end
end
Overflow.new.show # => 11.14.
谢谢!
【问题讨论】:
标签: ruby inheritance