Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do String comparison in Ruby? [duplicate]

Tags:

ruby

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.

like image 727
itsaboutcode Avatar asked Jan 06 '10 20:01

itsaboutcode


2 Answers

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.

like image 55
sepp2k Avatar answered Oct 14 '22 00:10

sepp2k


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.

like image 43
Beanish Avatar answered Oct 13 '22 23:10

Beanish