在某些語言中,您可以訪問對象的屬性而無需編寫自己的getter/setter方法。Ruby對象是否有內置的getter/setter方法?
對象是否內置了getter/setter和Ruby?
這裏是我嘗試:
class Obj
def initialize(color)
@color = color
end
end
t = Obj.new("red")
puts t.color
在某些語言中,您可以訪問對象的屬性而無需編寫自己的getter/setter方法。Ruby對象是否有內置的getter/setter方法?
對象是否內置了getter/setter和Ruby?
這裏是我嘗試:
class Obj
def initialize(color)
@color = color
end
end
t = Obj.new("red")
puts t.color
您正在尋找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"
我發現,這些方法似乎在Ruby中的所有對象存在:
t.instance_variable_set(:@color, "blue")
t.instance_variable_get(:@color)
這真的沒有意義,除非你動態設置名字,比如'instance_variable_set('@'+ name,'blue')' – tadman
感謝,這是比工作都是圍繞我發現我使用好得多。 –