2013-01-14 81 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 

欢迎来到元编程的魔力。 ;)