2

I have code in Ruby that defines a variable in a loop.

print("What difficulty do you want on a scale of 1-5?\n")
loop do
  difficulty = gets.to_i
  break if difficulty == 1 or difficulty == 2 or difficulty == 3 or difficulty == 4 or difficulty == 5
end
range = 10 if difficulty == 1
range = 100 if difficulty == 2
range = 500 if difficulty == 3
range = 1000 if difficulty == 4
range = 5000 if difficulty == 5

I get an error that the variable difficulty is undefined. I think this is an issue from the loop. and I do not know how to implement it into another form that would serve the same purpose. Is there a way that I could make the variable global? I have tried looking up other ways to make it in another format but nothing has helped.

1 Answer 1

2

You can define it outside the loop otherwise, it'd be scope-constrained.

Try:

difficulty_range = {
  1 => 10,
  2 => 100,
  3 => 500,
  4 => 1000,
  5 => 5000
}

difficulty = nil

loop do
  print("What difficulty do you want on a scale of 1-5?\n")
  difficulty = gets.to_i
  break if (1..5).include?(difficulty)
end

p difficulty_range[difficulty]
Sign up to request clarification or add additional context in comments.

Comments

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.