+ 1
How to use user input along with if statements?
puts "Enter your age." var2 = gets.chomp.to_i case var2 when var2 < 0 puts "How are you alive?" when var2 > 0 && var2 < 13 puts "You are not old enough." else puts "Enter your name." var1 = gets.chomp if var1 == "" puts "Please enter a name." else puts "Hello, #{var1}!" end end Why doesn't this work? The course puts if statements and user inputs separately, but what's the point of a user input if you can't render some of the inputs as invalid?
5 Answers
0
Good question. Case will evaluate whether each case option matches what you input in the beginning (var2). When entering (for example) -2, it is actually comparing in that first step the condition var2 < 0, to var2. In other words, var2 < 0 evaluates to true, and that is compared to the value of var2 (-2), and true is not equivalent to -2, so that case is evaluated as false!
A solution to try: remove var2 from the line beginning the case statement. Just say:
case
when var2 < 0
etc...
If that could be explained more clearly, check out this link:
https://tinyurl.com/yd99xty2
0
@André
Say I wanted to add a line that puts "Please enter an age." If the user doesn't input anything for the integer. How would I do that? Isn't var2=="" only for strings?
0
Yes, it is just for strings. Unless I'm mistaken, .to_i will convert a blank entry to 0.
Not sure it is the best option, but you could have var2 = gets.chomp, without the .to_i. Then you could have var2.to_i in each of the case statements, except for your 'when var2 == "" ' option.
0
@André
Ah, it seems to not be working. Even the name part that asks you to try again when you leave it blank isn't working. I'm going to complete more lessons before I try working on this again, I think. I had only gotten to arrays at the time of the question.
0
Sure, come back to it and message if you're still running into problems