如果您拥有的只是对象的引用,那么您无法干净利落地完成它.
def foo
bar @something
end
def bar(value)
value # no clean way to know this is @something
end
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一的黑客是遍历所有实例变量self
,寻找匹配.但这是一个非常混乱的方法,可能会很慢.
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'
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为instance_variables
返回一个符号数组,这些符号是实例变量的名称.
instance_variables
#=> [:@something, :@whatever]
Run Code Online (Sandbox Code Playgroud)
并instance_variable_get
允许您通过它的名称获取值.
instance_variable_get :@something # note the @
#=> 'abc123'
Run Code Online (Sandbox Code Playgroud)
结合这两种方法,您可以接近您想要的.
只是明智地使用它.在使用基于此的解决方案之前,看看您是否可以通过某种方式重构事物,这样就没有必要了.元编程就像一门武术.你应该知道它是如何工作的,但要尽可能避免使用它.
归档时间: |
|
查看次数: |
5417 次 |
最近记录: |