Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access instance variable using its name (as symbol)

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?
like image 952
jnv Avatar asked Mar 29 '11 22:03

jnv


People also ask

How do you name an instance variable?

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.

Which symbol is used to get the value of the instance variable?

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.

How can we access 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.

What should instance variables be declared as?

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.


1 Answers

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 
like image 166
Wes Avatar answered Nov 15 '22 06:11

Wes