可能重复:
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符号。
噢。当然,它已经回答:) –