Ruby on Rails - Avoid Instance Variables, Use Getters and Setters - ruby on rails tutorial - rails guides - rails tutorial - ruby rails
Instance Variables:
- An instance variable has a name beginning with @, and its scope is confined to whatever object self refers to.
- Two different objects, even if they belong to the same class, are allowed to have different values for their instance variables.
Getters and Setters:
- A getter is a method that gets the value of a specific property.
- A setter is a method that sets the value of a specific property.
- You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties.
- In Ruby, you can set and access instance variables like this:
- But you shouldn't. You should always use getter and setter methods like so:
- This is because instance variables never raise errors so this could happen to you:
- With getters and setters, you won't waste time tracking down bugs caused by spelling errors like the one above:
- You don't even need to write the getters and setters yourself, you can just use attr_accessor (or attr_writer or attr_reader if you only want one or the other).
- If you don't want to expose the getters or setters to the outside world then you can always make them private: