我很难理解Ruby中的attr_accessor。 有人能给我解释一下吗?
当前回答
Attr_accessor非常简单:
attr_accessor :foo
是以下操作的快捷方式:
def foo=(val)
@foo = val
end
def foo
@foo
end
它只不过是一个对象的getter/setter
其他回答
它只是一个为实例变量定义getter和setter方法的方法。一个示例实现如下:
def self.attr_accessor(*names)
names.each do |name|
define_method(name) {instance_variable_get("@#{name}")} # This is the getter
define_method("#{name}=") {|arg| instance_variable_set("@#{name}", arg)} # This is the setter
end
end
简单地说,它将为类定义setter和getter。
请注意,
attr_reader :v is equivalant to
def v
@v
end
attr_writer :v is equivalant to
def v=(value)
@v=value
end
So
attr_accessor :v which means
attr_reader :v; attr_writer :v
等效于为类定义setter和getter。
The main functionality of attr_accessor over the other ones is the capability of accessing data from other files. So you usually would have attr_reader or attr_writer but the good news is that Ruby lets you combine these two together with attr_accessor. I think of it as my to go method because it is more well rounded or versatile. Also, peep in mind that in Rails, this is eliminated because it does it for you in the back end. So in other words: you are better off using attr_acessor over the other two because you don't have to worry about being to specific, the accessor covers it all. I know this is more of a general explanation but it helped me as a beginner.
希望这对你有所帮助!
Attr_accessor非常简单:
attr_accessor :foo
是以下操作的快捷方式:
def foo=(val)
@foo = val
end
def foo
@foo
end
它只不过是一个对象的getter/setter
Attr_accessor只是一个方法。(这个链接应该提供更多关于它如何工作的见解——看看生成的方法对,一个教程应该告诉你如何使用它。)
关键在于,类在Ruby中不是定义(在c++和Java等语言中“只是定义”),而是求值的表达式。在此求值期间,调用attr_accessor方法,该方法反过来修改当前类——记住隐式接收器:self。其中self是此时“打开”的类对象。
对attr_accessor和friends的需求是:
像Smalltalk一样,Ruby不允许在该对象的method1之外访问实例变量。也就是说,不能像在Java甚至Python中那样以x.y形式访问实例变量。在Ruby中,y总是被当作一个要发送的消息(或“要调用的方法”)。因此attr_*方法创建包装器,通过动态创建的方法代理实例@变量访问。 样板很糟糕
希望这能澄清一些细节。快乐的编码。
1严格来说,这并不正确,有一些“技术”围绕这一点,但没有语法支持“公共实例变量”访问。
推荐文章
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 数组到哈希Ruby
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- 如何使用RSpec的should_raise与任何类型的异常?
- 如何创建退出消息
- 忽略GEM,因为没有构建它的扩展
- 在Gem::Specification.reset期间未解决的规格: