为什么我的类不能用 ruby​​ 运行?

发布于 2024-12-21 20:47:39 字数 469 浏览 1 评论 0原文

我正在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你列表最软的妹 2024-12-28 20:47:39

将文本更改为实例变量:

class Be
  def new_text
    @text = gets()
  end
  def show_text
    puts "#{@text}"
  end
end

您收到错误是因为 show_text 方法正在尝试访问名为 @text 的变量,该变量尚未在原始变量中定义例子。

Change text to be an instance variable:

class Be
  def new_text
    @text = gets()
  end
  def show_text
    puts "#{@text}"
  end
end

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文