We all know that the expression operator has only one input value. This is common in C and Java. Today we will discuss the unary operator overloading in Ruby.
Unary operators include: + -*! & Etc. To avoid confusion with the value +-, to overload the unary operator, add an @ operator to the end.
1. Example of a simple unary operator overload:-@ Operator
We use the String class as an example. The String is not defined by default-OPERATOR:
The Code is as follows:
1.9.3p125: 027> a = "Hello"
=> "Hello"
1.9.3p125: 028>-
NoMethodError: undefined method '-@' for "Hello": String
From (irb): 28
From ~ /. Rvm/rubies/ruby-1.9.3-p125/bin/irb: 16: in''
1.9.3p125: 029>
We use the Open Class method (Open Class can be referred to) to add the unary operation to the object of String type:
The Code is as follows:
1.9.3p125: 029> def a.-@; downcase; end;
1.9.3p125: 036>
=> "Hello"
1.9.3p125: 037>-
=> "Hello"
1.9.3p125: 038>
From the code above, we have added the-operator to object.
2. Other operators: + @,~, !
We use the Open Class Feature again to add the method to the String Class:
The Code is as follows:
#! /Usr/local/ruby/bin/ruby
Class String
Def -@
Downcase
End
Def + @
Upcase
End
Def ~
# Do a ROT13 transformation-http://en.wikipedia.org/wiki/ROT13
Tr 'a-Za-Z', 'N'-ZA-Mn-za-m'
End
Def to_proc
Proc. new {self}
End
Def to_a
[Self. reverse]
End
End
Str = "Teketa's Blog is GREAT"
Puts "-# {str }=#{-str }"
Puts "+ # {str }=#{+ str }"
Puts "~ # {Str }= #{~ Str }"
Puts "# {str}. to_a = # {str. to_a }"
Puts % w {a, B}. map & str
Puts * str
The running result of the above Code:
The Code is as follows:
-Teketa's Blog is GREAT = teketa's blog is great
+ Teketa's Blog is GREAT = TEKETA's BLOG IS GREAT
~ Teketa's Blog is GREAT = Grxrgn 'f Oybt vf TERNG
Teketa's Blog is GREAT. to_a = ["TAERG si golB s 'ateket"]
Teketa's Blog is GREAT
Teketa's Blog is GREAT
TAERG si golB s 'ateket
We noticed that the * and & operators are reloaded through to_a and to_proc. In Ruby, the * and & must be reloaded through the to_a and to_proc methods.