'How to tell users how many years they have left till 21
What I am trying to do is tell the your how many years they have left till there 21. I have been trying to think of it but nothing.
Here is my code:
#!/usr/bin/env ruby
under_age = 21
print "What is your first name? "
first_name = gets.chomp
print "What is your last name? "
last_name = gets.chomp
print "What is your age? "
user_age = Integer(gets.chomp)
if user_age < legal_age
print "You may not continue"
else if > 21
print "Welcome!"
Solution 1:[1]
You set this at the beginning:
under_age = 21
But then you don't use it, you use legal_age I think if you change the first line to
legal_age = 21
and then drop the last less-than like:
if user_age < legal_age
years_to_wait = 21 - user_age
print "You may not continue, come back in #{years_to_wait} year#{years_to_wait > 1? 's' : ''} "
else
print "Welcome!"
end
I added a little bit there that you may have not covered being new to Ruby. Just to be clear:
#{years_to_wait} inside of a double quote string (" vs ') prints out as the value of the variable. If the variable is 1, then the response would be the singular "year", if greater than 1 it would be plural "years". I used the very compact version of if/then/else to make it clean (called the Ternary operator).
The first part is the comparison followed by the ? for an implied "if"
years_to_wait > 1?
followed by the return value if true which is the character 's' then a ":" and the return value if false, no character ''. That gets us the correct version of the word "year(s)" when the interpolation happens.
Solution 2:[2]
Your variable names are all over the place. But I think you just want
legal_age - user_age
Also your last if is unnessary
Solution 3:[3]
You miss the variable in the elsif statement in ruby it should look:
if user_age < 21
print "You may not continue"
elsif user_age > 21
print "Welcome!"
end
the legal_age variable is also not assigned, maybe you mean the under_age variable instead.
Solution 4:[4]
your if..else syntax is not proper. for more info
if user_age < under_age
print "You may not continue, come back after #{under_age - user_age} years"
else
print "Welcome!"
end
Note: legal_age is also not assigned, you can replace it with under_age or change under_age to legal_age
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | karina |
| Solution 3 | ebimanuel |
| Solution 4 |
