我试图从自身得到一个方法名称:Ruby - 我怎样才能得到一个方法名称本身?
def funky_method
self.inspect
end
它返回“主”。
我该如何返回“funky_method”呢?
我试图从自身得到一个方法名称:Ruby - 我怎样才能得到一个方法名称本身?
def funky_method
self.inspect
end
它返回“主”。
我该如何返回“funky_method”呢?
下面是代码:
适用版本> = 1.9:
def funky_method
return __callee__
end
对于<版本1.9:
def funky_method
return __method__
end
很简单:
def foo
puts __method__
end
__callee__
返回当前方法的“被调用名称”,而__method__
返回当前方法的“定义名称”。
因此,与alias_method一起使用时,__method__
未返回预期结果。
class Foo
def foo
puts "__method__: #{__method__.to_s} __callee__:#{__callee__.to_s} "
end
alias_method :baz, :foo
end
Foo.new.foo # __method__: foo __callee__:foo
Foo.new.baz # __method__: foo __callee__:baz
同义词:'__method__' – steenslag
只有'__method__'将在1.8,工作'__callee__'配备了1.9 – UncleGene
所以,你说'__method__'不为Ruby版本> = 1.9的工作?根据Chetan Patil的回答,他们会产生不同的值,调用者与您所在的方法名称不同。 –