Ruby 定义操作符过程 [英] Ruby defining operator procedure

查看:36
本文介绍了Ruby 定义操作符过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 ruby​​ 中编写一个具有我可以这样调用的过程的类:

how can a write a class in ruby that has a procedures that i can call like this:

a = MyObj.new()
b =  MyObj.new()

c = a * b
d = a / b
e = a - b

这比:

c = a.multiply(b)
...

谢谢

推荐答案

你已经得到了关于如何定义二元运算符的答案,所以这里的小附录是你如何定义一元 -(比如负数).

You already got an answer on how to define the binary operators, so just as little addendum here's how you can define the unary - (like for negative numbers).

>  class String
..   def -@
..     self.swapcase
..   end
.. end #=> nil
>> -"foo" #=> "FOO"
>> -"FOO" #=> "foo"

这篇关于Ruby 定义操作符过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆