tags:

views:

446

answers:

5

I am using following code to compare string but its always takes me to else case, why it is so? its always printing else part which is "You have enter wrong abbreviation"

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 have same result.

+6  A: 

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.

sepp2k
+1 for the `case` suggestion. 100% agree!
Chris Jester-Young
+2  A: 

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.

Chris Jester-Young
A: 

gets returns what you typed with a newline. Try state_abbreviation = gets.chomp

Brian Young
A: 

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
makevoid
+7  A: 

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.

Beanish
Thanks for the vote of confidence! Much appreciated.
Chris Jester-Young
I would actually use an array, with an `in_array?(state)` or something of the sort. Unless hash has its own syntax like that.
Garrett
statehash[state_abbreviation] either returns a value so in my example RI or NC work, else nil is returned. Hashes do have .has_key?, .has_value? but I don't see the need to use that here.
Beanish