I am having a hard time understanding attr_accessor
in Ruby. Can someone explain this to me?
相关问题
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
- gem cleanup shows error: Unable to uninstall bundl
相关文章
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
- ruby - simplify string multiply concatenation
I think part of what confuses new Rubyists/programmers (like myself) is:
"Why can't I just tell the instance it has any given attribute (e.g., name) and give that attribute a value all in one swoop?"
A little more generalized, but this is how it clicked for me:
Given:
We haven't defined Person as something that can have a name or any other attributes for that matter.
So if we then:
...and try to give them a name...
We get an error because, in Rubyland, a Person class of object is not something that is associated with or capable of having a "name" ... yet!
BUT we can use any of the given methods (see previous answers) as a way to say, "An instance of a Person class (
baby
) can now have an attribute called 'name', therefore we not only have a syntactical way of getting and setting that name, but it makes sense for us to do so."Again, hitting this question from a slightly different and more general angle, but I hope this helps the next instance of class Person who finds their way to this thread.
It is just a method that defines getter and setter methods for instance variables. An example implementation would be:
attr_accessor
is very simple:is a shortcut for:
it is nothing more than a getter/setter for an object
Basically they fake publicly accessible data attributes, which Ruby doesn't have.
Simply put it will define a setter and getter for the class.
Note that
So
are equivalant to define a setter and getter for the class.
Simply
attr-accessor
creates thegetter
andsetter
methods for the specified attributes