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?
Here are ways to do both techniques. Assuming we already have your class definition,
The
Object#sendmethod accepts at least a symbol representing the name of the method to call, and call it. You can also pass arguments to the method after the name and a block, too.The second way to do this (using your
Position#getmethod) isI recommend this way because it encapsulates the technique for getting the values. Should you need to change it later, you don’t need to change all the code that uses
Position.