Ruby: Prefer Method Invocations over Instance Variables

  • Typo will raises NoMethodError; Instance variable returns nil
  • It is easier to see if you’re doing modifications
class A
  attr_reader :a

  def plus_5
    a + 5
  end

  def change
    @a = 1
  end
end

v.s.

class A
  def plus_5
    @a + 5
  end

  def change
    @a = 1
  end
end
  • Methods are more flexible. If you ever want to refactor the name, you need to update all references of instance variables. Changing method only needs to change its name.