在 Ruby 中,如何获取散列而不是数组中的实例变量?
我有一个 Ruby 课程。我想从该类中的方法的参数获取实例变量。我可以将所有实例变量作为数组获取:
self.instance_variables
但是,我想获取名为 arg
的实例变量,具体来说:
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
?
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
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')
How do I compute hash_of_instance_variables
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要创建所有实例变量的哈希,您可以使用以下代码:
但正如 cam 在他的评论中提到的,您应该使用
instance_variable_get
方法:To create a hash of all instance variables you can use the following code:
But as cam mentioned in his comment, you should use
instance_variable_get
method instead:问题很老,但找到了 Rails 解决方案: instance_values
这是第一个答案谷歌所以也许它会对某人有所帮助。
Question is quite old but found rails solution for this: instance_values
This is first answer in google so maybe it will help someone.
对于 Ruby 2.6+,您可以将块传递给
to_h
方法,导致语法非常 DRY:For Ruby 2.6+, you can pass a block to the
to_h
method, leading to very DRY syntax:Ruby on Rails 有几种内置方法可以实现此目的,您可能会发现它们可以满足您的需求。
Ruby on Rails has a couple of built-in ways to do this that you might find meet your needs.