将实例变量添加到Ruby中的类 [英] Adding an instance variable to a class in Ruby
问题描述
如何在运行时上将实例变量添加到已定义的类中,然后从该类外部获取并设置其值?
How can I add an instance variable to a defined class at runtime, and later get and set its value from outside of the class?
我正在寻找一种元编程解决方案,该解决方案允许我在运行时修改类实例,而不是修改最初定义该类的源代码.一些解决方案说明了如何在类定义中声明实例变量,但这不是我要问的.
I'm looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class. A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about.
推荐答案
您可以使用属性访问器:
You can use attribute accessors:
class Array
attr_accessor :var
end
现在您可以通过以下方式访问它:
Now you can access it via:
array = []
array.var = 123
puts array.var
请注意,您也可以使用attr_reader
或attr_writer
来仅定义吸气剂或设置器,也可以这样手动定义它们:
Note that you can also use attr_reader
or attr_writer
to define just getters or setters or you can define them manually as such:
class Array
attr_reader :getter_only_method
attr_writer :setter_only_method
# Manual definitions equivalent to using attr_reader/writer/accessor
def var
@var
end
def var=(value)
@var = value
end
end
如果只想在单个实例上定义它,也可以使用单例方法:
You can also use singleton methods if you just want it defined on a single instance:
array = []
def array.var
@var
end
def array.var=(value)
@var = value
end
array.var = 123
puts array.var
仅供参考,针对此答案的评论,单例方法很好用,以下是证明:
FYI, in response to the comment on this answer, the singleton method works fine, and the following is proof:
irb(main):001:0> class A
irb(main):002:1> attr_accessor :b
irb(main):003:1> end
=> nil
irb(main):004:0> a = A.new
=> #<A:0x7fbb4b0efe58>
irb(main):005:0> a.b = 1
=> 1
irb(main):006:0> a.b
=> 1
irb(main):007:0> def a.setit=(value)
irb(main):008:1> @b = value
irb(main):009:1> end
=> nil
irb(main):010:0> a.setit = 2
=> 2
irb(main):011:0> a.b
=> 2
irb(main):012:0>
如您所见,单例方法setit
会设置与使用attr_accessor定义的字段相同的字段@b
.因此,单例方法是解决此问题的完美方法.
As you can see, the singleton method setit
will set the same field, @b
, as the one defined using the attr_accessor... so a singleton method is a perfectly valid approach to this question.
这篇关于将实例变量添加到Ruby中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!