Ruby定义运算符过程
如何在ruby中编写一个具有我可以调用的过程的类,如下所示:
a = MyObj.new() b = MyObj.new() c = a * b d = a / b e = a - b
这比以下更好:
c = a.multiply(b) ...
谢谢
你已经得到了关于如何定义二元运算符的答案,所以就像你在如何定义一元的方法一样-
(就像负数一样)。
> class String .. def -@ .. self.swapcase .. end .. end #=> nil >> -"foo" #=> "FOO" >> -"FOO" #=> "foo"
class Foo attr_accessor :value def initialize( v ) self.value = v end def *(other) self.class.new(value*other.value) end end a = Foo.new(6) #=> # b = Foo.new(7) #=> # c = a*b #=> #
您可以在此处找到可定义为方法的运算符列表:
http://phrogz.net/ProgrammingRuby/language.html#operatorexpressions
只需创建名称为要重载的运算符的方法,例如:
class MyObj def / rhs # do something and return the result end def * rhs # do something and return the result end end
在Ruby中, *
运算符(以及其他此类运算符)实际上只是调用与运算符同名的方法。 所以要覆盖*
,你可以这样做:
class MyObj def *(obj) # Do some multiplication stuff true # Return whatever you want end end
您可以对其他运算符使用类似的技术,例如/
或+
。 (请注意,您无法在Ruby中创建自己的运算符。)