Jacob
Jacob

Reputation: 6477

How can I check a word is already all uppercase?

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

Upvotes: 29

Views: 30307

Answers (4)

JCorcuera
JCorcuera

Reputation: 6834

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

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

Upvotes: 55

Ole Spaarmann
Ole Spaarmann

Reputation: 16751

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!

Upvotes: 4

Gishu
Gishu

Reputation: 136633

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

Upvotes: 2

PeterWong
PeterWong

Reputation: 16011

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.

Upvotes: 28

Related Questions