1. 程式人生 > >Ruby中的一元操作符(-,+,*,&,!)的過載

Ruby中的一元操作符(-,+,*,&,!)的過載

一元操作大家都知道,就是表示式的操作符只有一個輸入值。這個在C和Java中都很常見。今天我們要探討一下Ruby中的一元操作符過載。
一元操作符有:+ – * ! & 等,為了避免與數值的 + – 混淆,過載一元操作符,要在後面加上一個 @ 操作符。

1. 一個簡單的一元操作符過載例子:[email protected] 操作符
我們以String類為例子。String預設沒有定義 – 操作符:

1.9.3p125 :027 > a = "Hello"
=> "Hello"
1.9.3p125 :028 > -a
NoMethodError: undefined method `

[email protected]' for "Hello":String
from (irb):28
from ~/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `'
1.9.3p125 :029 >

我們通過Open Class的方式(Open Class可參考)給型別為String的a物件,加上一元操作:

1.9.3p125 :029 > def [email protected];downcase;end;

1.9.3p125 :036 > a
=> “Hello”
1.9.3p125 :037 > -a
=> “hello”
1.9.3p125 :038 >

從上面程式碼看到我們已經將 – 這個操作符新增到了a物件中。

2. 其他的操作符:[email protected], ~, !
我們再次使用Open Class的特性,給String類加上方法:

1 #!/usr/local/ruby/bin/ruby
2
3 class String
4 def [email protected]
5 downcase
6 end
7
8 def [email protected]
9 upcase
10 end
11
12 def ~
13 # Do a ROT13 transformation - http://en.wikipedia.org/wiki/ROT13
14 tr 'A-Za-z', 'N-ZA-Mn-za-m'
15 end
16
17 def to_proc
18 Proc.new { self }
19 end
20
21 def to_a
22 [ self.reverse ]
23 end
24
25 end
26
27 str = "Teketa's Blog is GREAT"
28 puts "-#{str} = #{-str}"
29 puts "+#{str} = #{+str}"
30 puts "~#{str} = #{~str}"
31 puts "#{str}.to_a = #{str.to_a}"
32 puts %w{a, b}.map &str
33 puts *str


上面程式碼的執行結果:

-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

我們注意到,*和&操作符,是通過to_a 和 to_proc來過載的,在Ruby中,要過載*和&就是通過過載to_a和to_proc方法來實現的。