Why use Ruby's attr_accessor, attr_reader and attr_writer?

前端 未结 5 1115
走了就别回头了
走了就别回头了 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:25

    You don't always want your instance variables to be fully accessible from outside of the class. There are plenty of cases where allowing read access to an instance variable makes sense, but writing to it might not (e.g. a model that retrieves data from a read-only source). There are cases where you want the opposite, but I can't think of any that aren't contrived off the top of my head.

提交回复
热议问题