【问题标题】:undefined local variable or method `stop' for main:Object (NameError)main:Object (NameError) 的未定义局部变量或方法“停止”
【发布时间】:2015-12-15 00:39:05
【问题描述】:

当我试图为我的代码创建一个循环时,它突然问我这个:

main:Object (NameError) 的未定义局部变量或方法“停止”。

如何解决此错误?

loop do
  puts "Hello. I am a calculator. Please tell me your name."
  name = gets
  puts "Hi #{name}. Enter 1 to add, 2 to multiply, 3 to subtract, and 4 to divide."
  z = gets.chomp.to_i

  def addition
    puts "Please enter your first number"
    a = gets.chomp.to_i
    puts "Please enter your second number"
    b = gets.chomp.to_i
    puts a+b
  end

  def multiply
    puts "Please enter your first number"
    c = gets.chomp.to_i
    puts "Please enter your second number"
    d = gets.chomp.to_i
    puts c*d
  end

  def subtract
    puts "Please enter your first number"
    e = gets.chomp.to_i
    puts "Please enter your second number"
    f = gets.chomp.to_i
    puts e-f
  end

  def divide
    puts "Please enter your first number"
    h = gets.chomp.to_i
    puts "Please enter your second number"
    g = gets.chomp.to_i
    puts h/g
  end

  if z == 1
    puts addition
  elsif z == 2
    puts multiply
  elsif z == 3
    puts subtract
  elsif z == 4
    puts divide
  end

  puts "Would you like to calculate something else or stop?"
  choice = gets.chomp.to_s

  if choice == stop
    break
  end
end

【问题讨论】:

  • 欢迎来到 Stack Overflow。请阅读您的问题,并想象您被同事问过同样的问题。你想看什么来帮助回答这个问题?将其添加到问题中。如果我们要为您提供任何详细的帮助,您的问题非常模糊,需要详细说明。
  • 抱歉代码有点奇怪
  • 停止应该是“停止”。如果您不将其括在引号中,系统会将其视为变量,这就是您收到该错误的原因。

标签: ruby loops


【解决方案1】:

问题是你有这个:

if choice == stop

我认为你的意思是使用:

if choice == 'stop'

【讨论】:

    猜你喜欢
    • 2016-02-14
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    相关资源
    最近更新 更多