当前位置: 移动技术网 > IT编程>脚本编程>Ruby > Ruby中对一元操作符重载实例

Ruby中对一元操作符重载实例

2017年12月08日  | 移动技术网IT编程  | 我要评论

一元操作大家都知道,就是表达式的操作符只有一个输入值。这个在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类加上方法:

复制代码 代码如下:

 #!/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


上面代码的运行结果:

复制代码 代码如下:

-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方法来实现的。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网