Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby NoMethodError O'Reilley示例_Ruby_Nomethoderror - Fatal编程技术网

Ruby NoMethodError O'Reilley示例

Ruby NoMethodError O'Reilley示例,ruby,nomethoderror,Ruby,Nomethoderror,通过O'reilley书中的课程部分进行学习,他们似乎指出以下内容应该有效: class Point def initialize(x,y) @x, @y = x, y end def x @x end def y @y end def to_s "(#@x,#@y)" end end p = Point.new(5,0) q = Point.new(p.x*2, p.y*2) q.x = 0 puts q.x 理论上,我

通过O'reilley书中的课程部分进行学习,他们似乎指出以下内容应该有效:

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

  def x
    @x
  end

  def y
    @y
  end

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

p = Point.new(5,0)
q = Point.new(p.x*2, p.y*2)
q.x = 0
puts q.x

理论上,我希望它打印0,而我的编译器在尝试执行q.x=0时返回NoMethodError。有什么东西冲着你们跳出来了吗?

该代码不应该工作,因为没有根据错误消息定义的方法x=了。在Ruby中,类的赋值操作是另一种方法,因此您应该在代码中添加以下内容:

class Point
  def x=(value)
    @x = value
  end

  def y=(value)
    @y = value
  end
end

q、 只有在Point类中有x的setter时,x=0才能工作

def x=(x)
  @x=x
end

@x、 @y应该是{@x},{@y}。不确定它是否一定是勘误表,但在文本中肯定没有明确定义,谢谢您的回复!