Kevin Cai
Kevin Cai

Reputation: 25

Ruby undefined variable

I have a code below:

secret_number = 8
user_input = ""

def number_guesser(user_input)
  while user_input != secret_number
    puts "Guess a number between 1 and 10:"
    user_input = gets.chomp

    if user_input != secret_number
      puts "Wrong! Try again."
    else
      puts "You guessed correctly!"
    end
  end
end

number_guesser(user_input)

when I tried to run the above program it showed as below:

****undefined local variable or method secret_number' for main:Object (repl):211:innumber_guesser' (repl):221:in `'****

Any ideas?

Upvotes: 0

Views: 89

Answers (1)

tadman
tadman

Reputation: 211740

You can't use a local variable like that inside another scope such as a method, it's two different contexts. Instead you need to pass that in if you want to use it.

It's a simple change:

def number_guesser(user_input, secret_number)
  # ...
end

Then just feed that argument in.

You'll note that user_input isn't really necessary as a parameter, you can always initialize and use that locally, so it's actually pointless as an argument.

The pattern to use in that case:

loop do
  input = gets.chomp

  # Prompting...

  break if input == secret_number

  # Guessed wrong...
end

Upvotes: 5

Related Questions