Trying to learn / understand Ruby setter and getter methods

You can interact with that instance variable from other methods belonging to that instance, even if there is no getter:

def noise=(noise)
  @noise = noise
end

def last_noise
  @noise
end

There doesn’t need to be a getter defined with the same name as the method; the two are not linked at all. The getter is needed to “get” the value of the instance variable, but only in a short syntax.

What’s happening in your example is that you’re initializing a new object (Human.new), and then using a method (noise=, yes the method name contains the = symbol) that just-so-happens to define an instance variable (that is, a variable just for that instance), and then finally retrieving that instance variable with another method call.

You can actually use instance_variable_get to get the instance variable without defining any getter at all:

man = Human.new
man.noise = "Howdie"
man.instance_variable_get("@noise")

This will return “Howdie”, even though there is no getter defined.

And no, I don’t think he’s using an older version of Ruby.

Leave a Comment