Difference between __callee__ and __method__

后端 未结 3 1488
挽巷
挽巷 2021-02-18 20:30

In Ruby, one can use either

__callee__ 

or

__method__ 

to find the name of the currently executing method.<

3条回答
  •  礼貌的吻别
    2021-02-18 21:26

    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.

提交回复
热议问题