NoMethodError O'Reilley 示例
浏览 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,相反,我的编译器在尝试时返回 NoMethodError
执行qx = 0
。你们有什么事情跳出来吗?
Working through the classes section in the O'reilley book and they seem to be indicating the below should work:
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
In theory, I'm expecting it to print 0, instead my compiler is returning a NoMethodError
upon trying to perform q.x = 0
. Anything jumping out at you guys?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该代码不应该工作,因为没有定义方法
x=
(根据错误消息)。网上可能有勘误表吗?That code should not work, as there is no method
x=
defined (as per the error message). There might be an errata online?在 Ruby 中,类的赋值操作是另一种方法,因此您应该在代码中添加以下内容:
In Ruby, an assignment operation for classes is yet another method, so that you should add following to your code:
qx = 0 仅当 Point 类中有 x 的 setter 时才有效
q.x = 0 can work only when you have a setter for x in Point class