Search code examples
rubyclassoopobjectdesign-patterns

Ruby: How should I access instance variables inside a class?


In ruby you can internally access variables directly via @var_name or via private getters attr_reader :var_name.

Which solution is more (semantically?) correct? Any advantages/disadvantages of using either solution 1 or solution 2?

Solution 1:

class Point
 def initialize(x, y)
   @x = x
   @y = y
 end

 def distance
   Math.sqrt(@x ** 2 + @y ** 2)
 end
end

Solution 2:

class Point
  def initialize(x, y)
   @x = x
   @y = y
  end

  def distance
    Math.sqrt(x ** 2 + y ** 2)
  end

private 
  attr_reader :x, :y

end

Solution

  • I would use the second option:

    class Point
      def initialize(x, y)
       @x = x
       @y = y
      end
    
      def distance
        Math.sqrt(x ** 2 + y ** 2)
      end
    
    private 
    
      attr_reader :x, :y    
    end
    

    For two reasons:

    1. attr_reader might be faster (as Filip Bartuzi already pointed out)
    2. Using attr_reader might make it easier to refactor that class later on by replacing the attr_reader with a custom getter method.