attr vs attr_accessor [英] attr vs attr_accessor
问题描述
在Ruby中,实例变量attr
,attr_reader
,attr_writer
和attr_accessor
有四种不同的getter和setter方法.问题是,是否在Ruby attr :dilithium
中与attr_reader :dilithium
相同,并且如果传递了附加参数true,则与attr_accessor :dilithium
相同吗?那就是
In Ruby there are four different getter and setter methods for instance variables, attr
, attr_reader
, attr_writer
, and attr_accessor
. The question is, is in Ruby attr :dilithium
, the same as attr_reader :dilithium
, and identical to attr_accessor :dilithium
if an additional parameter true is passed? That is to say is
class Enterprise
attr :dilithium, true
与
class Enterprise
attr_accessor :dilithium
两个功能attr
和attr_accessor
或多或少是多余的吗?
Are the two functions attr
and attr_accessor
more or less redundant?
推荐答案
一个区别是attr_accessor
和朋友更加清晰,并且attr
的可选布尔参数现在为
One difference is that attr_accessor
and friends are clearer, and the optional boolean argument to attr
is now deprecated. Other than that, and the fact that attr
has no documentation, there's no real difference.
这篇关于attr vs attr_accessor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!