为什么我的类不能用 ruby 运行?
我正在 IRB 中测试我的代码,并输入了以下内容:
class be
def new_text
text = gets()
end
def show_text
puts "#{text}"
end
end
当我输入 new_text 时,它起作用了,但是当我输入 show_text 时,它出现了错误:
NameError: undefined local variable or method `text' for #<BE:0xd3cc08>
from (irb):14:in `show'
from (irb):14:in `show'
from C:/Program Files/Ruby1.9.2/bin/irb:12:in `<main>'
关于如何解决该问题的任何想法?
I was testing my code in IRB and I typed in this:
class be
def new_text
text = gets()
end
def show_text
puts "#{text}"
end
end
When I typed in new_text it worked but when I typed in show_text it came up with an error:
NameError: undefined local variable or method `text' for #<BE:0xd3cc08>
from (irb):14:in `show'
from (irb):14:in `show'
from C:/Program Files/Ruby1.9.2/bin/irb:12:in `<main>'
Any ideas of how to fix that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将文本更改为实例变量:
您收到错误是因为
show_text
方法正在尝试访问名为@text
的变量,该变量尚未在原始变量中定义例子。Change text to be an instance variable:
You're getting the error because the
show_text
method is trying to access a variable called@text
which hadn't been defined in your original example.