Enter an instance of the instance using its name (as a character)

In Ruby, I have this class: <Preview> class Position attr_reader :x, :y def initialize(x, y) @x, @y = x, y end end I want to access the variables x and y with the symbol, something like this: <Preview> 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 that I found with this code, I can achieve a 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?
+6
variables ruby class
source share
2 answers

Here are ways to do both methods. Assuming we already have a class definition,

 position = Position.new(1, 2) axis = :x position.send axis #=> 1 axis = :y position.send axis #=> 2 

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 #=> 1 axis = :y position.get axis #=> 2 

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.

+2
source share

Just use the send method

 class Position attr_reader :x, :y def initialize(x, y) @x, @y = x, y end end => nil pos = Position.new(5,5) => #<Position:0x0000010103d660 @x=5, @y=5> axis = :x => :x pos.send axis => 5 
+8
source share

All Articles