Alias Methods

One way of avoiding ambiguity when you use similarly named methods from multiple modules is to alias those methods. An alias is a copy of an existing method with a new name. You use the alias keyword followed by the new name and then the old name:

alias  happyexpression expression

You can also use alias to make copies of methods that have been overridden so that you can specifically refer to a version prior to its overridden definition:

alias_methods.rb

module Happy
    def Happy.mood
        return "happy"
    end

    def expression
        return "smiling"
    end
    alias happyexpression expression
end

module Sad
    def Sad.mood
        return "sad"
    end

    def expression
        return "frowning"
    end
    alias sadexpression expression
end

class Person
    include Happy
    include Sad
    attr_accessor :mood
    def initialize
        @mood = Happy.mood
    end
end

p2 = Person.new
puts(p2.mood)                 #=> happy
puts(p2.expression)           #=> frowning
puts(p2.happyexpression)      #=> smiling
puts(p2.sadexpression)        #=> frowning
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.173.53