How do I do String comparison in Ruby? [duplicate]
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?开发者_JAVA技巧("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.
Before the big block, say:
state_abbreviation.chomp!
As an alternative to sepp2k's excellent suggestion to use case
, consider making a hash with the state abbreviations as keys.
gets
returns what you typed with a newline. Try state_abbreviation = gets.chomp
You are using gets, and probably your shell/input is adding a newline (\n) character at the end of the string, and maybe you may want to use the case statement:
example:
print("Enter your state abbreviation: ")
state_abbreviation = gets.strip
case state_abbreviation
when "NC" then puts("North Carolina")
when "SC" then puts("South Carolina")
# ...
else puts("You have enter wrong abbreviation")
end
While we're off topic and commenting on the approach vs. the problem, check out this rails cast. He pulls in all the state abbreviations from a website. I'm a fan of this because it gets the mappings out of your code entirely (though might be a good idea to save the site, just in case). You could then put that together with a cache to prevent actually hitting the DB.
http://railscasts.com/episodes/179-seed-data
http://railscasts.com/episodes/115-caching-in-rails-2-1
精彩评论