attr_accessor 如何在 Ruby on Rails 中工作 [英] How does attr_accessor work in 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
它创建了一个空用户,我可以通过
it creates an empty user and I can assign its name and email by
example.name = "something"
example.email = "something"
我的问题是,为什么这个东西有效?计算机如何知道example.name 表示类中的@name 变量?我假设 name 和 :name 是不同的,在代码中我们没有明确告诉计算机 example.name 等同于 :name 符号.
My question is, why this thing works? How does the computer know that example.name means the @name variable in the class? I'm assuming name and :name are different, and here in the code we have not explicitly told the computer that example.name is equivalent to :name symbol.
推荐答案
attr_accessor :field
与调用 attr_reader :field
和 attr_writer :field<相同/代码>.那些又大致等于:
attr_accessor :field
is the same as calling attr_reader :field
and attr_writer :field
. Those in turn are roughly the equal to:
def field
@field
end
def field=(value)
@field = value
end
欢迎使用元编程的魔力.;)
Welcome to the magic of meta-programming. ;)
这篇关于attr_accessor 如何在 Ruby on Rails 中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!