2013-01-14 84 views
0

可能重複:
What is attr_accessor in Ruby?如何Ruby on Rails中attr_accessor工作

這裏的示例代碼:

class User 
    attr_accessor :name, :email 

    def initialize(attributes = {}) 
    @name = attributes[:name] 
    @email = attributes[:email] 
    end 

.... 

end 

當我做

example = User.new 

它創建一個空的用戶,我可以通過

example.name = "something" 
example.email = "something" 

我的問題是,爲什麼這個事情的作品賦予它的名字和電子郵件?計算機如何知道example.name意味着類中的@name變量?我假設name和name是不同的,在代碼中,我們沒有明確地告訴計算機example.name等同於:name符號。

+0

噢。當然,它已經回答:) –

回答

5

attr_accessor所做的是創建了幾個方法,一個getter和一個setter。它使用您傳遞的符號來構造方法名稱和實例變量。你看,這代碼:

class User 
    attr_accessor :name 
end 

相當於這段代碼

class User 
    def name 
    @name 
    end 

    def name=(val) 
    @name = val 
    end 
end 
4

attr_accessor :field是與調用attr_reader :fieldattr_writer :field。這些大致等於:

def field 
    @field 
end 

def field=(value) 
    @field = value 
end 

歡迎來到元編程的魔力。 ;)