有没有办法覆盖类的运算符,通过在模块内创建一个新的运算符方法,然后将该模块混合到类中?
例如,这会覆盖Fixnum的+运算符:
class Fixnum
def +(x)
product = x
product = product * self
return product
end
end
p 3 + 3
# => 9
Run Code Online (Sandbox Code Playgroud)
这不会覆盖Fixnum的+运算符:
module NewOperators
def +(x)
product = x
product = product * self
return product
end
end
class Fixnum
include NewOperators
end
p 3 + 3
# => 6
Run Code Online (Sandbox Code Playgroud) ruby ×1