在Ruby中,如何获取实例变量而不是数组的哈希值? [英] In Ruby, how can I get instance variables in a hash instead of an array?

查看:116
本文介绍了在Ruby中,如何获取实例变量而不是数组的哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Ruby class. I want to get an instance variable from an argument to a method in that class. I can do get all of the instance variables as an array:

self.instance_variables

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

However, I want to get the instance variable named arg, specifically:

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

object.get_instance_variable('my_instance_var')

如何计算hash_of_instance_variables?

推荐答案

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

To create a hash of all instance variables you can use the following code:

class Object
  def instance_variables_hash
    Hash[instance_variables.map { |name| [name, instance_variable_get(name)] } ]
  end
end

但是正如 cam 在他的评论中提到的那样,您应该改用instance_variable_get方法:

But as cam mentioned in his comment, you should use instance_variable_get method instead:

object.instance_variable_get :@my_instance_var

这篇关于在Ruby中,如何获取实例变量而不是数组的哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆