Ruby运算符重载

Ruby运算符重载教程

在 Ruby 类中,我们可以重新实现运算符的功能,这叫做运算符重载。

案例

运算符重载

运算符重载的使用

#!/usr/bin/ruby -w # -*- coding : utf-8 -*- puts "HaiCoder(www.haicoder.net)" class Box def initialize(w,h) # 初始化 width 和 height @width,@height = w, h end def +(other) # 定义 + 来执行向量加法 Box.new(@width + other.width, @height + other.height) end def -@ # 定义一元运算符 - 来对 width 和 height 求反 Box.new(-@width, -@height) end def *(scalar) # 执行标量乘法 Box.new(@width*scalar, @height*scalar) end end

这里,我们重载了 +、- 和 * 运算符。

Ruby运算符重载总结

在 Ruby 类中,我们可以重新实现运算符的功能,这叫做运算符重载。