ruby - Why do we need attr_accessor? -


i fail understand why needed attr_reader , attr_writer, or attr_accessor declared in class. read both this , this posts, posts explain how work, not as why there.

in case of

class person   attr_accessor :age end  bob = person.new bob.age = 99 bob.age 

it seems little redundant having tell ruby write , read age, while not being able write , read instance variable outside class automatically. why need set reader , writer in class instead of following code , save few lines?

class person end  bob = person.new bob.age = 99 bob.age  

because makes code easier maintain.

this way clear reading class code expect have happen, , expect other classes access these variables.

without outside code access internal variables, , if refactor code , remove or rename such variable outside code breaks.

thus accessor methods make clear intend other classes access these methods

fyi: ruby powerful, , if want can go ahead , make work way want. don't recommend pointing out understand explicit choice being made of keeping code readable. if want see how read on, , try running code...

<script type="text/ruby">    def puts(s)  # ignore method, dumps display    element['#output'].html = element['#output'].html + s.to_s + "<br/>"  end    class openkimono    def method_missing(name, *args)      if name =~ /=$/        instance_variable_set("@#{name[0..-2]}".to_sym, args[0])      else        instance_variable_get("@#{name}")      end    end  end    class myclass < openkimono  end    foo = myclass.new    foo.bar = 12    puts "foo.bar set 12, = #{foo.bar}"    foo.baz = 13    puts "foo.baz set 13, = #{foo.baz}"    puts "foo.manchu has never been set... equal? #{foo.manchu}"    </script>      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <script src="https://rawgit.com/reactive-ruby/inline-reactive-ruby/master/inline-reactive-ruby.js"></script>  <div id="output" style="font-family: courier"></div>


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -