Ruby - Module Alias Methods

Introduction

One way of avoiding method ambiguity 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  happytalk talk

You can 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:

Demo

module Happy
    def Happy.mood
        return "happy"
    end# from   w w  w.j ava 2  s.c om

    def talk
        return "smiling"
    end
    alias happytalk talk
end

module Sad
   def Sad.mood
       return "sad"
   end

   def talk
       return "frowning"
   end
   alias sadtalk talk
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.talk)           #=> frowning
puts(p2.happytalk)      #=> smiling
puts(p2.sadtalk)        #=> frowning

Result

Related Topic