Ruby’s Redefinition of Subscript Methods

  question, ruby

I am studying the book Ruby Basic Tutorial and testing the code examples in the book. There is a redefinition code about array subscript method. There was an error during debugging:

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

The whole example code is as follows:

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

May I ask why there is an error message saying that the assignment method is not defined?

Because you really have no definition#x=

attr_reader :x, :yDefine only#x,#y

You can either redefine it#x=And#y=, or putself.x = valChange to@x = val