I am having a hard time understanding attr_accessor
in Ruby.
Can someone explain this to me?
Ruby – attr_accessor in Ruby
ruby
Related Topic
- Ruby-on-rails – How to understand nil vs. empty vs. blank in Ruby
- Ruby-on-rails – Understanding the Rails Authenticity Token
- Ruby – How to write a switch statement in Ruby
- Ruby – How to check if a value exists in an array in Ruby
- Ruby – Blocks and yields in Ruby
- Ruby-on-rails – Difference between attr_accessor and attr_accessible
- Ruby: How to install a specific version of a ruby gem
- PHP: Instantiate class by reference
Best Answer
Let's say you have a class
Person
.Obviously we never defined method
name
. Let's do that.Aha, we can read the name, but that doesn't mean we can assign the name. Those are two different methods. The former is called reader and latter is called writer. We didn't create the writer yet so let's do that.
Awesome. Now we can write and read instance variable
@name
using reader and writer methods. Except, this is done so frequently, why waste time writing these methods every time? We can do it easier.Even this can get repetitive. When you want both reader and writer just use accessor!
Works the same way! And guess what: the instance variable
@name
in our person object will be set just like when we did it manually, so you can use it in other methods.That's it. In order to understand how
attr_reader
,attr_writer
, andattr_accessor
methods actually generate methods for you, read other answers, books, ruby docs.