ruby - 使用名称访问实例变量(作为符号)

标签 ruby class variables

在 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/

相关文章:

ruby - 如何从 Ruby 程序发送邮件?

ruby-on-rails - 我应该允许 activerecord-import 运行多长时间?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

javascript - 在 else 语句中看不到 if 语句的 jQuery javascript 变量

mysql - 使用默认值更新 Sequel 模型

ruby-on-rails - Rails - 如何禁用所有控制台日志记录?

class - 如何重写magento core-cache-model (Mage_Core_Model_Cache)

python - 当我使用 dir([user-defined object]) 时,为什么它还会返回对象父类的命名空间中的名称?

java - 如何获取数组来引用类

powershell - 在Powershell中使用子脚本修改父脚本中的变量