2010-09-12 44 views
10

我想使用attr_accessor將數組作爲實例變量。attr_accessor for array?

但不是attr_accessor只適用於字符串?

如何在數組上使用它?

更新:

例如:如果你想:

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

那麼你必須自己創建這些方法?

+4

attr_accessor適用於任何對象。你試過了嗎?什麼地方出了錯? – Douglas 2010-09-12 00:52:09

+0

@Douglas:看看更新 – 2010-09-12 01:02:06

+1

如果你定義了一個'foo ='方法,這樣在執行'x.foo = bar'後,'x.foo'不會返回'bar',你會混淆任何人誰使用你的班級。爲什麼不只是做'object.array <<「貓」'? – sepp2k 2010-09-12 01:11:45

回答

13

回覆您的更新:

雖然你可以實現你描述作用的一類,它是非常不尋常的,並且可能會混淆使用該課程的任何人。

通常訪問器有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 
+0

+1作出解釋。我也喜歡<<方法。所以你可以寫object.array <<「貓」而不是推。這隻比object.array =「cat」多一個字符。 – Baju 2010-09-12 01:20:59

+4

是的,它也是有意義的,不像'object.array =「cat」',它完全是batty。 – 2010-09-12 01:25:32

1

它爲我的作品:

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] 
$ 
18
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] 
1

我認爲有這種用法的情況下。考慮

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表現爲你會預計噸,但你也可以獲得訪問過去的價值。