0

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?

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Furthermore, secret_number is an integer whereas input is a string, so you have to convert one or the other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.