我如何在Ruby中进行字符串比较?

前端之家收集整理的这篇文章主要介绍了我如何在Ruby中进行字符串比较?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用以下代码来比较字符串,但它总是把我带到其他地方.为什么?
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”),但我得到了相同的结果.

@R_404_323@

gets返回的字符串最后会有一个换行符.使用String#chomp删除它(即state_abbreviation = gets.chomp).

PS:如果您使用case-when而不是if-elsif-elsif,您的代码看起来会更清晰(恕我直言).

原文链接:https://www.f2er.com/ruby/274322.html

猜你在找的Ruby相关文章