In Ruby, I have this class:
class Position
attr_reader :x, :y
def initialize(x, y)
@x, @y = x, y
end
end
What I want to do is to access x and y variables using the symbol, something like this:
axis = :x
pos = Position.new(5,6)
#one way:
pos.axis # 5 (pos.x)
#other way:
pos.get(axis) # 5 (pos.x)
Thanks to this question I've found with this code, I can achieve the second behavior.
#...
class Position
def get(var)
instance_variable_get(("@#{var}").intern)
end
end
But it seems ugly and inefficient (especially converting symbol to string and back to symbol). Is there a better way?