在ruby中从自身获取实例变量名称 [英] get instance variable name from itself in ruby
问题描述
我有一个实例变量@foo
,我想写一些代码,以便得到字符串'foo'
I have an instance variable @foo
and I want to write some code so that I get string 'foo'
有任何提示吗?
推荐答案
如果所拥有的只是对对象的引用,则不能真正做到干净.
If all you have is a reference to the object, you can't really do it cleanly.
def foo
bar @something
end
def bar(value)
value # no clean way to know this is @something
end
我唯一想到的办法是遍历self
上的所有实例变量,寻找匹配项.但这是一个非常混乱的方法,可能会很慢.
The only hack I can think of is to loop through ALL instance variables on self
, looking for matches. But its a very messy approach that's likely to be slow.
def bar(value)
instance_variables.each do |ivar_name|
if instance_variable_get(ivar_name) == value
return ivar_name.to_s.sub(/^@/, '') # change '@something' to 'something'
end
end
# return nil if no match was found
nil
end
@something = 'abc123'
bar @something # returns 'something'
# But passing the same value, will return a value it's equal to as well
bar 'abc123' # returns 'something'
之所以可行,是因为instance_variables
返回的符号数组是实例变量的名称.
This works because instance_variables
returns an array of symbols that are the names of instance variables.
instance_variables
#=> [:@something, :@whatever]
instance_variable_get
和instance_variable_get
允许您通过名称获取值.
And instance_variable_get
allows you to fetch the value by it's name.
instance_variable_get :@something # note the @
#=> 'abc123'
结合使用这两种方法,您可以接近所需的内容.
Combine the two methods and you can get close to what you want.
明智地使用它.在使用基于此的解决方案之前,请先查看是否可以以某种方式重构事物,以使其不必要.元编程就像武术一样.您应该知道它是如何工作的,但是要有纪律避免在可能的情况下使用它.
Just use it wisely. Before using a solution based on this, see if you can refactor things a way so that it's not necessary. Meta-programming is like a martial art. You should know how it works, but have the discipline to avoid using it whenever possible.
这篇关于在ruby中从自身获取实例变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!