关于在ruby中覆盖+运算符的问题

aos*_*sik 7 ruby overriding operators addition

最近在这里转换为Ruby.以下问题并不真实; 这是关于Ruby内部如何工作的更多问题.是否可以覆盖标准加法运算符以接受多个输入?我假设答案是否定的,因为加法运算符是标准运算符,但我想确保我没有遗漏某些东西.

下面是我快速编写的代码,用于验证我的想法.请注意,这完全是微不足道的/做作的.

class Point
    attr_accessor :x, :y

    def initialize(x,y)
        @x, @y = x, y
    end


    def +(x,y)
        @x += x
        @y += y
    end


    def to_s
        "(#{@x}, #{@y})"
    end
end

pt1 = Point.new(0,0)
pt1 + (1,1) # syntax error, unexpected ',', expecting ')'
Run Code Online (Sandbox Code Playgroud)

Cha*_*tni 11

实现+operator 时,不应该改变对象.而是返回一个新的Point Object:

class Point
    attr_accessor :x, :y

    def initialize(x,y)
        @x, @y = x, y
    end


    def +(other)
      Point.new(@x + other.x, @y + other.y)
    end


    def to_s
        "(#{@x}, #{@y})"
    end
end

ruby-1.8.7-p302:
> p1 = Point.new(1,2)
=> #<Point:0x10031f870 @y=2, @x=1> 
> p2 = Point.new(3, 4)
=> #<Point:0x1001bb718 @y=4, @x=3> 
> p1 + p2
=> #<Point:0x1001a44c8 @y=6, @x=4> 
> p3 = p1 + p2
=> #<Point:0x1001911e8 @y=6, @x=4> 
> p3
=> #<Point:0x1001911e8 @y=6, @x=4> 
> p1 += p2
=> #<Point:0x1001877b0 @y=6, @x=4> 
> p1
=> #<Point:0x1001877b0 @y=6, @x=4> 
Run Code Online (Sandbox Code Playgroud)


sep*_*p2k 5

您可以+像这样定义方法,但您只能使用正常的方法调用语法来调用它:

pt1.+(1,1)
Run Code Online (Sandbox Code Playgroud)