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
def sum_of_squares; instance_variables.reduce(0) { |t,v| t + instance_variable_get(v) ** 2 }; end, thenPoint.new(3,5).sum_of_squares #=> 34. Object#instance_variables returns an array of the instance variables.attr_readeris just a shortcut to avoid writing the same, simple and generic getter methods for every attribute. It's part of DRY, imo.