Ruby关于下标方法重定义的问题
迷茫
迷茫 2017-04-24 09:13:36
0
1
906

正在学习《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

请问为什么会出现说赋值方法没有定义的错误提示?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全員に返信(1)
迷茫

実際に #x= を定義していないからです#x=

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

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

attr_reader :x, :y#x#y のみを定義します#🎜🎜# #🎜🎜##x=#y= を定義するか、self.x = val@ x に変更することができます。 = val#🎜🎜#
いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!