Difference between __callee__ and __method__

南楼画角 提交于 2020-06-10 07:33:06

问题


In Ruby, one can use either

__callee__ 

or

__method__ 

to find the name of the currently executing method.

What is the difference between the two?


回答1:


__method__ looks up the name statically, it refers to the name of the nearest lexically enclosing method definition. __callee__ looks up the name dynamically, it refers to the name under which the method was called. Neither of the two necessarily needs to correspond to the message that was originally sent:

class << (foo = Object.new)
  def bar(*) return __method__, __callee__ end
  alias_method :baz, :bar
  alias_method :method_missing, :baz
end

foo.bar # => [:bar, :bar]
foo.baz # => [:bar, :baz]
foo.qux # => [:bar, :method_missing]



回答2:


To paraphrase the documentation, __callee__ is the name of the method that the caller called, whereas __method__ is the name of the method at definition. The following example illustrates the difference:

class Foo

  def foo
    puts __callee__
    puts __method__
  end

  alias_method :bar, :foo
end

If I call Foo.new.foo then the output is

foo
foo

but if I call Foo.new.bar then the output is

bar
foo

__method__ returns :foo in both cases because that is the name of the method as defined (i.e. the class has def foo), but in the second example the name of the method the caller is calling is bar and so __callee__ returns that.




回答3:


__method__ returns defined name, and __callee__ returns called name. They are same usually, but different in a aliased method.

def foo
[__method__, __callee__]
end
alias bar foo
p foo #=> [:foo, :foo]
p bar #=> [:foo, :bar]

link



来源:https://stackoverflow.com/questions/35391160/difference-between-callee-and-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!