If,else and elseif - ARGH why doesn't my code work?


#1

Please can some one tell me why this is wrong?

print "what is your age?"
user_input = gets.chomp
if user_input < 18
print "You can not use this site as you are underage."
elsif user_input > 18
print "You may enter!"
else
print "You are 18!"
end


#2

Because the user input is a string, which you can validate by adding:

puts user_input.is_a? String

Now, you want to cast the input to a integer:

print "what is your age?"
user_input = gets.chomp
user_input = user_input.to_i
puts user_input.is_a? Integer 
if user_input < 18
    print "You can not use this site as you are underage."
elsif user_input > 18
    print "You may enter!"
else 
    print "You are 18!"
end

#3

Thank you for your help, I appreciate it


#4

Is this argument explained in a ruby lesson?
"user_input" is a standard terms/word? what is exactly ".is_a?", it's just a declaration?
and how long is long? Why in follow code it isn't necessary to write what is a string?
i'm sorry.

print "What's your first name?"
first_name = gets.chomp
first_name.capitalize!

print "What's your last name?"
last_name = gets.chomp
last_name.capitalize!

print "What city are you from?"
city = gets.chomp
city.capitalize!

print "What state or province are you from?"
state = gets.chomp
state.upcase!

puts "Your name is #{first_name} #{last_name} and you're from #{city}, #{state}!"

thanks


#5

I don't think it is.. not sure, has been ages since i done the ruby course on codecademy.

Now, user_input is just a variable, but i like logic names for variables (good programming habit) and well, user_input is a good name for variable to store input from the user.

.is_a? is a build in ruby function, you can use it to check data type (string, integer, Boolean, and so on) it is: is_a? Integer would translate to pseudo code in: is a integer? or is a string? it is almost a english question, in code form, how nice

By default, the user input is a string in ruby:

print "What's your first name?"
first_name = gets.chomp
print first_name.is_a? String
first_name.capitalize!

So there is no need to cast it to a string (since it already is a string)


#6

ops, for sure "user_input" is s a variable. My inattention .
indeed, it's logic to declare the user input will be a number, so user_input can be follows by "less/greater than" signs.

i'm (very) noob but very interested and curious
thank you again


#7

well, it is a string by default. So, you need to cast it to a integers, then you can use greater/lesser then


#9