0x4a6f4672 0x4a6f4672 - 1 year ago 47
Ruby Question

attr vs attr_accessor

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


identical to

class Enterprise
attr_accessor :dilithium


Are the two functions
attr
and
attr_accessor
more or less redundant?

Answer Source

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.