【问题标题】:question on overriding + operator in ruby关于在 ruby​​ 中覆盖 + 运算符的问题
【发布时间】:2011-06-01 17:40:03
【问题描述】:

这里最近转换为 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 ')'

【问题讨论】:

    标签: ruby operators overriding addition


    【解决方案1】:

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

    pt1.+(1,1)
    

    【讨论】:

      【解决方案2】:

      您可以使用数组实现类似的功能:

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

      然后将其用作:

      pt1 + [1, 1]
      

      您还可以将它与 Chandra 的解决方案结合使用,以同时接受数组和点作为参数。

      【讨论】:

        【解决方案3】:

        在实现+ 运算符时,您不应该改变对象。而是返回一个新的点对象:

        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> 
        

        【讨论】:

        • 我同意这种实现方式,因为它最有意义,但这更像是一种缓慢的工作实验
        猜你喜欢
        • 2011-12-22
        • 1970-01-01
        • 2011-03-04
        • 1970-01-01
        • 2011-04-17
        • 1970-01-01
        • 2010-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多