Here are ways to do both methods. Assuming we already have a class definition,
position = Position.new(1, 2) axis = :x position.send axis
The Object#send method takes at least a character representing the name of the method to call, and calls it. You can also pass arguments to the method after the name and block.
The second way to do this (using your Position#get method) is
class Position def get(axis) send axis end end position = Position.new(1, 2) axis = :x position.get axis
I recommend this way because it encapsulates a method of getting values. If you need to change it later, you do not need to change all the code that Position uses.
Tom
source share