访问者在Ruby on Rails中工作

可能重复:
Ruby中的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符号。


attr_accessor所做的是创建几个方法,一个getter和一个setter。 它使用您传递的符号来构造方法名称和实例变量。 看,这个代码:

class User
  attr_accessor :name
end

相当于这个代码

class User
  def name
    @name
  end

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

attr_accessor :field与调用attr_reader :fieldattr_writer :field 。 这些反过来大致等于:

def field
  @field
end

def field=(value)
  @field = value
end

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

链接地址: http://www.djcxy.com/p/25771.html

上一篇: accessor work in Ruby on Rails

下一篇: Getting local variable names defined inside a method from outside the method