Should I use alias or alias_method?

后端 未结 7 1680
再見小時候
再見小時候 2020-11-30 16:25

I found a blog post on alias vs. alias_method. As shown in the example given in that blog post, I simply want to alias a method to another within t

相关标签:
7条回答
  • 2020-11-30 17:10

    Apart from the syntax, the main difference is in the scoping:

    # scoping with alias_method
    class User
    
      def full_name
        puts "Johnnie Walker"
      end
    
      def self.add_rename
        alias_method :name, :full_name
      end
    
    end
    
    class Developer < User
      def full_name
        puts "Geeky geek"
      end
      add_rename
    end
    
    Developer.new.name #=> 'Geeky geek'
    

    In the above case method “name” picks the method “full_name” defined in “Developer” class. Now lets try with alias.

    class User
    
      def full_name
        puts "Johnnie Walker"
      end
    
      def self.add_rename
        alias name full_name
      end
    end
    
    class Developer < User
      def full_name
        puts "Geeky geek"
      end
      add_rename
    end
    
    Developer.new.name #=> 'Johnnie Walker'
    

    With the usage of alias the method “name” is not able to pick the method “full_name” defined in Developer.

    This is because alias is a keyword and it is lexically scoped. It means it treats self as the value of self at the time the source code was read . In contrast alias_method treats self as the value determined at the run time.

    Source: http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html

    0 讨论(0)
提交回复
热议问题