attr vs attr_accessor

后端 未结 3 1325
无人及你
无人及你 2020-12-15 05:31

In Ruby there are four different getter and setter methods for instance variables, attr, attr_reader, attr_writer, and attr_acce

相关标签:
3条回答
  • 2020-12-15 06:06

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-15 06:15

    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.

    0 讨论(0)
提交回复
热议问题