我很难理解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
属性访问器attr_accessor提供了两个免费方法。
就像在Java中,它们被称为getter和setter。
很多答案都给出了很好的例子,所以我就简单点。
# the_attribute
and
# the_attribute =
在旧的ruby文档中,#表示方法。 它还可以包含一个类名前缀… MyClass # my_method
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是一个简单的方法,可以帮助我们清理(DRY-ing)重复的getter和setter方法。 这样我们就可以更专注于编写业务逻辑而不用担心setter和getter。
我认为让新手和程序员(比如我自己)困惑的部分原因是:
“为什么我不能告诉实例它有任何给定的属性(例如,名称),并一次性为该属性赋值?”
更一般化一点,但这就是我的想法:
考虑到:
class Person
end
我们还没有将Person定义为可以有名称或任何其他属性的东西。
那么如果我们
baby = Person.new
...试着给它们起个名字…
baby.name = "Ruth"
我们得到一个错误,因为在Rubyland中,对象的Person类不是与“名称”相关联或不具有“名称”的东西……然而!
但是我们可以使用任何给定的方法(参见前面的回答)来说明,“Person类(baby)的实例现在可以有一个名为'name'的属性,因此我们不仅有了获取和设置该名称的语法方法,而且这样做对我们来说是有意义的。”
再一次,从一个稍微不同和更一般的角度来解决这个问题,但我希望这有助于Person类的下一个实例找到这个线程的方法。
推荐文章
- 是否可以在MiniTest中运行单个测试?
- 如何在Ruby中生成a和b之间的随机数?
- 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
- 如何在Ruby中创建文件
- 什么是Ruby文件。开放模式和选项?
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- Ruby中“or”和||的区别?
- 如何测试参数是否存在在轨道
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- RVM不是一个函数,用' RVM use…’不会起作用
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法