数组的attr_accessor?

我想使用attr_accessor将数组作为实例变量。

但是不仅仅是字符串attr_accessor吗?

我如何在arrays上使用它?

更新:

例如。 如果你想:

 object.array = "cat" object.array = "dog" pp object.array => ["cat", "dog"] 

那你必须自己创建这些方法吗?

你的更新:

虽然你可以实现一个按你所描述的方式运行的类,但这很不寻常,并且可能会混淆使用该类的任何人。

通常访问者有setter和getter。 当你使用setter设置某些内容时,你会从getter中得到同样的东西。 在下面的示例中,您将获得与getter完全不同的内容。 您应该使用add方法,而不是使用setter。

 class StrangePropertyAccessorClass def initialize @data = [] end def array=(value) # this is bad, use the add method below instead @data.push(value) end def array @data end end object = StrangePropertyAccessorClass.new object.array = "cat" object.array = "dog" pp object.array 

add方法如下所示:

  def add(value) @data.push(value) end ... object.add "cat" object.add "dog" pp object.array 
 class SomeObject attr_accessor :array def initialize self.array = [] end end o = SomeObject.new o.array.push :a o.array.push :b o.array << :c o.array.inspect #=> [:a, :b, :c] 

这个对我有用:

 class Foo attr_accessor :arr def initialize() @arr = [1,2,3] end end f = Foo.new p f.arr 

返回以下内容

 $ ruby /tmp/t.rb [1, 2, 3] $ 

我认为有这种用法的情况。 考虑

 begin result = do_something(obj) # I can't handle the thought of failure, only one result matters! obj.result = result rescue result = try_something_else(obj) # okay so only this result matters! obj.result = result end 

然后是

 # We don't really care how many times we tried only the last result matters obj.result 

然后对于我们的专业人士

 # How many times did we have to try? obj.results.count 

所以,我会:

 attr_accessor :results def initialize @results = [] end def result=(x) @results << x end def result @results.last end 

这样, result就像您期望的那样,但您也可以获得访问过去值的好处。