我正在自學 Ruby,但遇到了一些我不太了解的東西。我得到了一個錯誤branchingcalc.rb:53:in `<main>': undefined local variable or method `userChoice' for main:Object (NameError)
在我的代碼(下面)中,我在上面的方法中定義了 userChoice。我遇到的問題是它是在上面的方法中定義的,還是 if/elsif 樹不能讀取變數,因為它是在方法中定義的?
我已經洗掉了 userInput 方法,將其放在#Begining 部分,這解決了我的問題,但是,我希望 calc 是可重復的。
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
uj5u.com熱心網友回復:
您已經userChoice在方法中引入了變數userInput。此變數僅存在于該方法中。如果您想在方法之外傳達此資訊,最好的選擇是從方法中回傳它,然后稍后使用該回傳值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/484990.html
標籤:红宝石
