How can I check a word is already all uppercase in Ruby?

旧时模样 提交于 2019-11-28 10:43:40

You can compare the string with the same string but in uppercase:

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

Hope this helps

a = "Go234"
a.match(/\p{Lower}/) # => #<MatchData "o">

b = "GO234"
b.match(/\p{Lower}/) # => nil

c = "123"
c.match(/\p{Lower}/) # => nil

d = "µ"
d.match(/\p{Lower}/) # => #<MatchData "µ">

So when the match result is nil, it is in uppercase already, else something is in lowercase.

Thank you @mu is too short mentioned that we should use /\p{Lower}/ instead to match non-English lower case letters.

I am using the solution by @PeterWong and it works great as long as the string you're checking against doesn't contain any special characters (as pointed out in the comments).

However if you want to use it for strings like "Überall", just add this slight modification:

utf_pattern = Regexp.new("\\p{Lower}".force_encoding("UTF-8"))

a = "Go234"
a.match(utf_pattern) # => #<MatchData "o">

b = "GO234"
b.match(utf_pattern) # => nil

b = "ÜÖ234"
b.match(utf_pattern) # => nil

b = "Über234"
b.match(utf_pattern) # => #<MatchData "b">

Have fun!

Gishu

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!