我使用下面的代码来比较字符串,但它总是将我带到else。为什么?
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我也尝试过.eql?("string"),但我得到了同样的结果。
发布于 2010-01-07 05:00:54
gets返回的字符串将在末尾换行。使用String#chomp删除它(即state_abbreviation = gets.chomp)。
PS:如果你使用case-when而不是if-elsif-elsif,你的代码看起来会更整洁(IMHO)。
发布于 2010-01-07 05:12:21
我没有足够的观点来评论,但我认为Chris Jester-Young的散列想法真的很棒。
statehash = { "RI" => "Rhode Island", "NC" => "North Carolina" }
print "Enter your state abbreviation: "
state_abbreviation = gets.chomp.upcase
puts statehash[state_abbreviation]这段代码比一堆elsif更简洁明了,也比一个案例短得多。它还允许状态对象的散列,其中键是缩写,值是对象。
发布于 2010-01-07 05:01:00
在大块之前,说:
state_abbreviation.chomp!作为Sepp2k提出的使用case的绝佳建议的替代方案,可以考虑使用状态缩写作为键进行散列。
https://stackoverflow.com/questions/2016169
复制相似问题