I am using the following code to compare strings but it always takes me to the else
. Why?
print("Enter your state abbreviation: ")
state_abbreviation = gets
if state_abbreviation.upcase == "NC"
puts("North Carolina")
elsif state_abbreviation.upcase == "SC"
puts("Sourth Carolina")
elsif state_abbreviation.upcase == "GA"
puts("Georgia")
elsif state_abbreviation.upcase == "FL"
puts("Florida")
elsif state_abbreviation.upcase == "AL"
puts("Alabama")
else
puts("You have enter wrong abbreviation")
end
I also have tried .eql?("string")
but I get the same result.
The string returned by gets will have a linebreak at the end. Use String#chomp
to remove it (i.e. state_abbreviation = gets.chomp
).
PS: Your code would look much cleaner (IMHO) if you used case-when instead of if-elsif-elsif.
I don't have enough points to comment, but I think the hash idea by Chris Jester-Young is really neat.
statehash = { "RI" => "Rhode Island", "NC" => "North Carolina" }
print "Enter your state abbreviation: "
state_abbreviation = gets.chomp.upcase
puts statehash[state_abbreviation]
this code is a lot more concise and clear than a bunch of elsif and shorter than a case. It also allows for a hash of state objects, where the key is the abbreviation and the value is the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With