Difference between __callee__ and __method__

后端 未结 3 1634
挽巷
挽巷 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:04

    __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]
    

提交回复
热议问题