首頁  >  問答  >  主體

Ruby關於下標方法重定義的問題

正在學習《Ruby基礎教程》一書,同時測試書上的程式碼例子,其中有一個關於數組下標方法的重定義程式碼,在調試的時候出現錯誤:

point.rb:46:in `[]=': undefined method `x=' for (4, 7):Point (NoMethodError)
    from point.rb:70:in `<main>'
    

整個範例程式碼如下:

class Point
    attr_reader :x, :y

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

    def  inspect
        "(#{x}, #{y})"    
    end

    def +(other)
        self.class.new(x + other.x, y + other.y)
    end

    def -(other)
        self.class.new(x - other.x, y - other.y)
    end

    def -@
        self.class.new(-x, -y)
    end

    def +@
        dup
    end

    def ~@
        self.class.new(-y, x)
    end

    def [](index)
        case index
        when 0
            x
        when 1
            y
        else
            raise ArgumentError, "out of range '#{index}'"
        end
    end

    def []=(index,val)
        case index
        when 0
            self.x = val
        when 1
            self.y = val
        else
            raise ArgumentError, "out of range '#{index}'"    
        end
    end
end

point0 = Point.new(3,6)
point1 = Point.new(1,8)

p point0
p point1
p point0 + point1
p point0 - point1

p +point0
p -point0
p ~point0

point = Point.new(4,7)
p point[0]
p point[1]
point[0] = 2

請問為什麼會出現說賦值方法沒有定義的錯誤提示?

迷茫迷茫2710 天前908

全部回覆(1)我來回復

  • 迷茫

    迷茫2017-04-24 09:15:36

    因為你真的沒有定義#x=

    attr_reader :x, :y只定义#x, #y

    你要嘛再定義#x=#y=, 要么把self.x = val改成@x = val#y=, 要嘛把self.x = val改成@x = val

    回覆
    0
  • 取消回覆