DEV Community

Discussion on: Ruby Getters and Setters

Collapse
 
tadman profile image
Scott Tadman • Edited

These are also called "accessors" (read) and "mutators" (write) in other languages, but the principle is the same. Useful terminology for those coming to Ruby from places where those terms are used instead.

Ruby's way of declaring them as x= type methods is fairly unique and makes for some extremely concise code since there's no need for getX / setX pairs, it's just x and x=.

Another thing worth mentioning is if you have a "setter" or attr_writer you can't use that without prefixing it with some kind of object, even self.

For example:

class Example
  attr_accessor :test

  def assign!
    test = :assigned
  end
end

example = Example.new
example.assign!
example.test
# => nil

That's because in the code test = :assigned creates a variable named test, it doesn't call the test= method. To use those you must do self.test = :assigned inside the context of that method or example.test = :assigned by using some kind of variable for reference.

This leads to a lot of confusion in places like ActiveRecord where assigning to the auto-generated attributes "doesn't work".