Q&A about the _method_ meaning?

来源:互联网 发布:linux 命令下载文件 sz 编辑:程序博客网 时间:2024/06/05 00:47
<Q>In the file lib/find.rb (1.9.3):
   def find(*paths) # :yield: path
         block_given? or return enum_for(__method__, *paths)
          ...........


<A>Kernel#__method__ returns the name of the method being defined as asymbol (or nil if called outside a method definition). In that case itreturns :find.Kernel#__callee__ is similar, but it returns the name of the method asused by the caller in that particular invocation. In that case thereturned symbol could be different if the caller invoked an alias.The benefit of not hard-coding the method name is similar to nothard-coding a constant name in code like    self.class.class_methodYou just do not rely on the constant name of the object's class andthe code has one less dependency in case of a refactor.Similarly, you could hard-code :find, it would not be the end of theworld, but __method__ makes that unnecessary. If it is computable,better not to repeat it.

0 0
原创粉丝点击