Aliasing a Method in Ruby

Programming laptop screen and lit keyboard on a black background.

Aliasing a Method,To alias a technique or variable name in Ruby is to create a 2nd name for the method or variable. Aliasing may be used both to offer extra expressive options to the programmer the use of the magnificence or to assist override techniques and exchange the conduct of the class or item. Ruby presents this capability with the “alias” and “alias_method” keywords.

Aliasing a Method,Create a Second Name

The alias key-word takes arguments: the antique approach name and the new method call. The method names must be exceeded as labels, instead of strings. Labels are used to consult methods and variables with out immediately referencing them.

If you’re a new Ruby programmer, the concept of labels may additionally seem odd, but each time you notice a label like “:methodname,” simply examine it as “the aspect called methodname.” The following example broadcasts a new elegance and creates an alias for the on approach referred to as begin.

#!/usr/bin/env ruby
magnificence Microwave
def on
places “The microwave is on”
end
alias :start :on
end
m = Microwave.New
m.Start # identical as m.On

Change the Behavior of a Class

There can be instances while you need to alternate the behavior of a class after it’s been declared. You can alias and upload new methods to an present elegance through growing 2nd magnificence statement that has the equal call as the existing class assertion.

You can also add aliases and techniques to character items the use of a syntax similar to the inherited magnificence syntax. The conduct of any class may be modified via developing an alias for any technique after which growing a brand new technique (with the unique approach call) that calls the technique with the alias.

In the following instance, a microwave elegance is declared and an instance is created. The second elegance assertion uses the alias technique to alternate the conduct of the “on” method that allows you to upload a warning message.

The 0.33 elegance declaration is used to exchange the behavior of the precise microwave example to add a good more stern caution. When aliasing a method a couple of instances, make sure to apply one of a kind technique names to keep the vintage method.

#!/usr/bin/env rubyclass Microwave
def on places “Microwave is on” stop endm = Microwave.Newm.Onclass Microwave alias :old_on1 :on
def on places “Warning: Do no longer insert metal gadgets!” old_on1 stop cease
m.OnMessage for this precise microwaveclass

< def on
puts “This microwave is susceptible, upload extra time”
old_on2
stop
stop
m.On # Displays greater message
m2 = Microwave.New
m2.On # Does now not display greater messag