Why use Ruby's attr_accessor, attr_reader and attr_writer?

前端 未结 5 1133
走了就别回头了
走了就别回头了 2020-11-22 14:51

Ruby has this handy and convenient way to share instance variables by using keys like

attr_accessor :var
attr_reader :var
attr_writer :var

5条回答
  •  孤独总比滥情好
    2020-11-22 15:29

    All of the answers above are correct; attr_reader and attr_writer are more convenient to write than manually typing the methods they are shorthands for. Apart from that they offer much better performance than writing the method definition yourself. For more info see slide 152 onwards from this talk (PDF) by Aaron Patterson.

提交回复
热议问题