Unary operation we all know that the expression operator has only one input value. This is common in both C and Java. Today we'll explore the unary operator overload in Ruby.
Unary operators are: +–*! &, in order to avoid confusion with numerical +–, overload unary operators, followed by an @ operator.
1. A simple unary operator overload example:-@ operator
we use the string class as an example. string is not defined by default-operator:
Copy Code code as follows:
1.9.3p125:027 > A = "Hello"
=> "Hello"
1.9.3p125:028 >-A
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 to refer to) to a object of type string, plus a unary operation:
Copy Code code as follows:
1.9.3p125:029 > Def a.-@;d owncase;end;
1.9.3p125:036 > A
=> "Hello"
1.9.3p125:037 >-A
=> "Hello"
1.9.3p125:038 >
See from the above code that we have added the-this operator to the A object.
2. Other operators: +@, ~,!
again, we use the attributes of the Open class to add a method to the string class:
Copy Code code 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:
Copy Code code 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 note that the * and & operators are overloaded by To_a and To_proc, and in Ruby, overloading * and & is accomplished by overloading the to_a and To_proc methods.