How can I check a word is already all uppercase?

后端 未结 4 2162
滥情空心
滥情空心 2020-12-06 09:16

I want to be able to check if a word is already all uppercase. And it might also include numbers.

Example:

GO234 => yes
Go234 => no
         


        
4条回答
  •  天命终不由人
    2020-12-06 10:12

    You could either compare the string and string.upcase for equality (as shown by JCorc..)

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

    OR

    you could call arg.upcase! and check for nil. (But this will modify the original argument, so you may have to create a copy)

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

    Update: If you want this to work for unicode.. (multi-byte), then string#upcase won't work, you'd need the unicode-util gem mentioned in this SO question

提交回复
热议问题