attr vs attr_accessor attr vs attr_accessor ruby ruby

attr vs attr_accessor


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.


In Ruby 1.8, attr can define only a single attribute, with an optional true to create a setter . In 1.9 it behaves like attr_reader:it allows for multiple attributes. As @Linuxios says, the optional boolean is deprecated.


If you look at the C code in Ruby 2.3.0, you will see that attr and attr_reader are actually doing the same thing (except for the deprecated code path). They are essentially equivalent functions.

For me, the main differences are:

attr is a bit easier to write down as it's shorter. I like the way it feels in the context of functional/immutable programming too (in those contexts, attr_writer and attr_accessor are irrelevant and thus using attr_reader feels verbose and redundant).

attr with multiple instance variables makes it hard to document, except in very specific situations, e.g.

# The coordinates in WGS84.attr :x, :y# The location name.attr :name# The popularity of the location.attr :popularity

It would be harder to document :name and :popularity independently if they were on the same line attr :name, :popularity.

Apart from that it boils down to personal preference. There is in practice no performance difference or any other difference.