学习编码,未定义变量的麻烦

Learning to code, Undefined variable troubles

我正在自学 Ruby,我遇到了一些我不太明白的事情。我收到 branchingcalc.rb:53:in `<main>': undefined local variable or method `userChoice' for main:Object (NameError)

的错误

在我的代码(下方)中,我在上面的方法中定义了 userChoice。我遇到的问题是它是在上面的方法中定义的,还是 if/elsif 树不能读取变量,因为它是在方法中定义的?

我删除了 userInput 方法,将其放在#Begining 部分,这解决了我的问题,但是,我希望计算是可重复的。

def userInput
    puts "Enter the first number"
    num1 = gets.chomp
    puts "Enter the second number"
    num2 = gets.chomp
    puts "What would you like to do?"
    puts "1 - Muiltiply"
    puts "2 - Divide"
    puts "3 - Add"
    puts "4 - Subtract"
    puts "5 - Exit"
    25.times { print "-" }
    puts
    userChoice = gets.chomp   # <- variable defined here
    puts
end

# Begining

puts "Branching Clac"
25.times { print "-" }
puts
puts userInput

# Choice tree

if userChoice == "1"          # <- undefined variable error here
 # ...
elsif userChoice == "2"
 # ...
end

您在 userInput 方法中引入了 userChoice 变量。该变量仅存在于该方法中。如果您想在方法之外传达此信息,最好的选择是从方法中 return 它,然后在以后使用该 return 值。