我如何在 Ruby 中进行字符串比较? [英] How do I do String comparison in Ruby?

查看:70
本文介绍了我如何在 Ruby 中进行字符串比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来比较字符串,但它总是将我带到 else.为什么?

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

我也试过 .eql?("string") 但我得到了相同的结果.

I also have tried .eql?("string") but I get the same result.

推荐答案

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

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:如果您使用 case-when 而不是 if-elsif-elsif,您的代码看起来会更简洁(恕我直言).

PS: Your code would look much cleaner (IMHO) if you used case-when instead of if-elsif-elsif.

这篇关于我如何在 Ruby 中进行字符串比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆