2017-07-20 61 views

回答

6

您正在尋找attr_accessor :color,如果你只想要磨自動生成的getter/setter方法的運行。

爲此模塊定義一個命名屬性,其中名稱爲symbol.id2name,創建實例變量(@name)和相應的訪問方法來讀取它。還創建一個名爲name =的方法來設置屬性。字符串參數被轉換爲符號。

,如果你不希望能夠設置類

之外的價值還有隻是一個attr_reader :color創建實例變量和相應的方法,返回每個實例變量的值。

attr_writer :color如果你想在課堂外設置但不能讀取。

創建訪問器方法以允許分配給該屬性。

class Obj 
    attr_accessor :color 

    def initialize(color) 
    @color = color 
    end 
end 

t = Obj.new("red") 
t.color #=> "red" 
+0

感謝,這是比工作都是圍繞我發現我使用好得多。 –

0

我發現,這些方法似乎在Ruby中的所有對象存在:

t.instance_variable_set(:@color, "blue") 
t.instance_variable_get(:@color) 
+0

這真的沒有意義,除非你動態設置名字,比如'instance_variable_set('@'+ name,'blue')' – tadman

相關問題