Raj Kumar Raj Kumar -4 years ago 84
Ruby Question

How to create an alias for operators in ruby


I read that alias keyword is used to create alias for methods,
operators and global variables.


My question is how to create alias for oprators?


I am using ruby version: ruby 1.9.3p551 (2014-11-13 revision 48407)
[i686-linux]


Answer Source

Here's an example for aliasing + :

class Fixnum
  alias_method :my_plus, :+
end

puts 2.my_plus(3) #=> 5

Note:

The correct, full syntax for 2+3 is 2.+(3), because + is just a method defined for Fixnums.

It can also be called as 2+3 or 2 + 3, which is just syntactic sugar. As far as I know, it's not possible to add syntactic sugar to new methods.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download