Home > Mobile >  Learning to code, Undefined variable troubles
Learning to code, Undefined variable troubles

Time:06-01

I am in the process of teaching myself Ruby, and I came onto something I don't quite understand. I am gettign an error of branchingcalc.rb:53:in `<main>': undefined local variable or method `userChoice' for main:Object (NameError)

In my code (below) I have userChoice defined in the method above it. Is the issue I'm having that it's defined in a method, above, or can the if/elsif tree not read the variable because it's defined in a method?

I have removed the userInput method, placing it in the #Begining portion, and that solves my issue, however, I would like the calc to be repeatable.

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

CodePudding user response:

You've introduced the userChoice variable in the userInput method. This variable only exists within that method. If you want to communicate this information outside of the method, the best option is to return it from the method, and then use that return value later.

  •  Tags:  
  • ruby
  • Related