如何检查一个单词在Ruby中已经全部大写?

我希望能够检查一个单词是否全部是大写的。 它也可能包括数字。

例:

GO234 => yes Go234 => no 

您可以将字符串与相同的字符串进行比较,但是大写:

 'go234' == 'go234'.upcase #=> false 'GO234' == 'GO234'.upcase #=> true 

希望这可以帮助

 a = "Go234" a.match(/\p{Lower}/) # => # b = "GO234" b.match(/\p{Lower}/) # => nil c = "123" c.match(/\p{Lower}/) # => nil d = "µ" d.match(/\p{Lower}/) # => # 

因此,当匹配结果为nil时,它已经是大写的,否则是小写的。

谢谢@mu太短了,我们应该使用/ \ p {Lower} /来匹配非英文小写字母。

我正在使用@PeterWong的解决方案,只要您检查的字符串不包含任何特殊字符(如注释中所指出),它就可以正常工作。

但是,如果你想将它用于像“Überall”这样的字符串,只需添加这个稍微修改:

 utf_pattern = Regexp.new("\\p{Lower}".force_encoding("UTF-8")) a = "Go234" a.match(utf_pattern) # => # b = "GO234" b.match(utf_pattern) # => nil b = "ÜÖ234" b.match(utf_pattern) # => nil b = "Über234" b.match(utf_pattern) # => # 

玩得开心!

您可以比较字符串和string.upcase是否相等(如JCorc所示..)

 irb(main):007:0> str = "Go234" => "Go234" irb(main):008:0> str == str.upcase => false 

要么

你可以调用arg.upcase! 检查没有。 (但这会修改​​原始参数,因此您可能需要创建副本)

 irb(main):001:0> "GO234".upcase! => nil irb(main):002:0> "Go234".upcase! => "GO234" 

更新:如果你想让它用于unicode ..(多字节),那么字符串#upcase不起作用,你需要在这个SO问题中提到的unicode-util gem