我想使用attr_accessor
将数组作为实例变量。attr_accessor for array?
但不是attr_accessor
只适用于字符串?
如何在数组上使用它?
更新:
例如:如果你想:
object.array = "cat"
object.array = "dog"
pp object.array
=> ["cat", "dog"]
那么你必须自己创建这些方法?
我想使用attr_accessor
将数组作为实例变量。attr_accessor for array?
但不是attr_accessor
只适用于字符串?
如何在数组上使用它?
更新:
例如:如果你想:
object.array = "cat"
object.array = "dog"
pp object.array
=> ["cat", "dog"]
那么你必须自己创建这些方法?
回复您的更新:
虽然你可以实现你描述作用的一类,它是非常不寻常的,并且可能会混淆使用该课程的任何人。
通常访问器有setter和getters。当你使用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
+1作出解释。我也喜欢<<方法。所以你可以写object.array <<“猫”而不是推。这只比object.array =“cat”多一个字符。 – Baju 2010-09-12 01:20:59
是的,它也是有意义的,不像'object.array =“cat”',它完全是batty。 – 2010-09-12 01:25:32
它为我的作品:
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]
$
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]
我认为有这种用法的情况下。考虑
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
表现为你会预计吨,但你也可以获得访问过去的价值。
attr_accessor适用于任何对象。你试过了吗?什么地方出了错? – Douglas 2010-09-12 00:52:09
@Douglas:看看更新 – 2010-09-12 01:02:06
如果你定义了一个'foo ='方法,这样在执行'x.foo = bar'后,'x.foo'不会返回'bar',你会混淆任何人谁使用你的班级。为什么不只是做'object.array <<“猫”'? – sepp2k 2010-09-12 01:11:45