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?
Instance variable names begin with an underscore ( _ ) followed by a camel case alphanumeric string. The first character following the underscore must be a lowercase letter; numerals are not permitted.
That captures self , which is the symbol :fn , which, on invocation, tells obj to execute the method fn , which returns the value of the instance variable.
Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name.
Instance variables can be accessed in any method of the class except the static method. Instance variables can be declared as final but not static. The instance Variable can be used only by creating objects only. Every object of the class has its own copy of Instance variables.
Easy, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With