在Ruby中,如何在哈希而不是数组中获取实例变量?

Tot*_*.js 10 ruby ruby-on-rails instance-variables

我有一个Ruby类.我想从参数获取一个实例变量到该类中的方法.我可以将所有实例变量作为数组获取:

self.instance_variables
Run Code Online (Sandbox Code Playgroud)

但是,我想获取名为的实例变量arg,具体如下:

class MyClass
  def get_instance_variable(arg)
    hash_of_instance_variables[arg]
  end
end

object.get_instance_variable('my_instance_var')
Run Code Online (Sandbox Code Playgroud)

我该如何计算hash_of_instance_variables

Yos*_*ssi 19

要创建所有实例变量的哈希,可以使用以下代码:

class Object
  def instance_variables_hash
    Hash[instance_variables.map { |name| [name, instance_variable_get(name)] } ]
  end
end
Run Code Online (Sandbox Code Playgroud)

但是,随着凸轮在他的评论中提到的,你应该使用instance_variable_get替代方法:

object.instance_variable_get :@my_instance_var
Run Code Online (Sandbox Code Playgroud)


suf*_*leR 7

问题很老但是找到了rails解决方案:instance_values

这是谷歌的第一个答案,所以它可能会帮助某人.