Getters and Setters
Since we are often getting (that is, retrieving) and setting (that is, assigning) variables with objects, it's common to define the methods that get and set those variables. In the previous section, the name
method was a getter, and the set_name
method was the setter.
Getting and setting variables are quite a common occurrence, and Ruby has a number of different ways for us to set and get variables. One quick improvement is to rewrite the setter method to use the assignment operator.
Let's consider the following example:
class User   def initialize(name)     @name = name   end   def name     @name   end   def name=(new_name)     @name = new_name   end end u = User.new("Suzanne") u.name = "Suzie"
The output will be as follows:
Adding...