在 Ruby 中,我有这个类:
class Position
attr_reader :x, :y
def initialize(x, y)
@x, @y = x, y
end
end
我想要做的是使用符号访问 x 和 y 变量,如下所示:
axis = :x
pos = Position.new(5,6)
#one way:
pos.axis # 5 (pos.x)
#other way:
pos.get(axis) # 5 (pos.x)
感谢this question我发现使用这段代码,我可以实现第二种行为。
#...
class Position
def get(var)
instance_variable_get(("@#{var}").intern)
end
end
但它看起来丑陋且效率低下(尤其是将符号转换为字符串并返回符号)。有没有更好的方法?
最佳答案
很简单,使用send
方法
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
关于ruby - 使用名称访问实例变量(作为符号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5479557/