Ruby中对一元操作符重载实例_ruby专题教程-查字典教程网
Ruby中对一元操作符重载实例
Ruby中对一元操作符重载实例
发布时间:2016-12-28 来源:查字典编辑
摘要:一元操作大家都知道,就是表达式的操作符只有一个输入值。这个在C和Java中都很常见。今天我们要探讨一下Ruby中的一元操作符重载。一元操作符...

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

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新ruby专题学习
    热门ruby专题学习
    脚本专栏子分类