If-elsif-else statement not working

I tried this:

print “Type a number between 1 and 5.”
number_one = gets.chomp

if number_one == 1
puts “You picked 1!”
elsif number_one == 2
puts “You picked 2!”
elsif number_one == 3
puts “You picked 3!”
elsif number_one == 4
puts “You picked 4!”
elsif number_one == 5
puts “You picked 5!”
else
puts “The first number was not between 1 and 5!”
end

but every number I try always gets the same answer:

“The first number was not between 1 and 5!”

I am confused on this error. Please help. Thanks!

The method “gets” always returns a String, so your variable number_one
is a String, not a Fixnum. If you enter 1, you’ll get “1”.
When you do the comparison number_one == 1, that means “1” == 1, which
is false.

Try this line instead of gets.chomp:
number_one = Integer(gets)

You can use also “case” and you can write this

number = gets.chomp.to_i
case number
when 1
puts “You picked 1!”
when 2
puts “You picked 2!”
when 3
puts “You picked 3!”
when 4
puts “You picked 4!”
when 5
puts “You picked 5!”
else
puts “The first number was not between 1 and 5!”
end

or more elegant

number = gets.chomp.to_i # <-- this convert your string to integer
case number
when 1; puts “You picked 1!”
when 2; puts “You picked 2!”
when 3; puts “You picked 3!”
when 4; puts “You picked 4!”
when 5; puts “You picked 5!”
else
puts “The first number was not between 1 and 5!”
end

Well, if you wanted to avoid repeating yourself, there’s always:

number = Integer(gets)
case number
when (1…5); puts “You picked #{number}!”
else; “The first number was not between 1 and 5!”
end

Thank you for the help! The first answer helped the most.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs