首页 编程技术Ruby中的一元操作符(-,+,*,&,!)的重载

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

运维派隶属马哥教育旗下专业运维社区,是国内成立最早的IT运维技术社区,欢迎关注公众号:yunweipai
领取学习更多免费Linux云计算、Python、Docker、K8s教程关注公众号:马哥linux运维

一元操作大家都知道,就是表达式的操作符只有一个输入值。这个在C和Java中都很常见。今天我们要探讨一下Ruby中的一元操作符重载。
一元操作符有:+ – * ! & 等,为了避免与数值的 + – 混淆,重载一元操作符,要在后面加上一个 @ 操作符。

1. 一个简单的一元操作符重载例子:-@ 操作符
我们以String类为例子。String默认没有定义 – 操作符:

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 >

我们通过Open Class的方式(Open Class可参考)给类型为String的a对象,加上一元操作:

1.9.3p125 :029 > def a.-@;downcase;end;

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

从上面代码看到我们已经将 – 这个操作符添加到了a对象中。

2. 其他的操作符:+@, ~, !
我们再次使用Open Class的特性,给String类加上方法:

1 #!/usr/local/ruby/bin/ruby
2
3 class String
4 def -@
5 downcase
6 end
7
8 def +@
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方法来实现的。

本文链接:https://www.yunweipai.com/411.html

网友评论comments

发表回复

您的电子邮箱地址不会被公开。

暂无评论

Copyright © 2012-2022 YUNWEIPAI.COM - 运维派 京ICP备16064699号-6
扫二维码
扫二维码
返回顶部