开发者

Check if a string is all-capitals in Rails

开发者 https://www.devze.com 2022-12-21 06:29 出处:网络
I\'m looking to check if a string is all capitals in Rails. How would I go about doing that? I\'m writing my own custom pluralize helper method and I would something be passing words like \"WORD\" an

I'm looking to check if a string is all capitals in Rails. How would I go about doing that?

I'm writing my own custom pluralize helper method and I would something be passing words like "WORD" and sometimes "Word" - I want to test if my word is all caps so I can return "WORDS" - wit开发者_运维问答h a capital "S" in the end if the word is plural (vs. "WORDs").

Thanks!


Do this:

str == str.upcase

E.g:

str = "DOG"
str == str.upcase  # true
str = "cat"
str == str.upcase  # false

Hence the code for your scenario will be:

# In the code below `upcase` is required after `str.pluralize` to transform 
# DOGs to DOGS
str = str.pluralize.upcase if str == str.upcase


Thanks to regular expressions, it is very simple. Just use [[:upper:]] character class which allows all upper case letters, including but not limited to those present in ASCII-8.

Depending on what do you need exactly:

# allows upper case characters only
/\A[[:upper:]]*\Z/   =~ "YOURSTRING"

# additionally disallows empty strings
/\A[[:upper:]]+\Z/   =~ "YOURSTRING"

# also allows white spaces (multi-word strings)
/\A[[:upper:]\s]*\Z/ =~ "YOUR STRING"

# allows everything but lower case letters
/\A[^[:lower:]]*\Z/  =~ "YOUR 123_STRING!"

Ruby doc: http://www.ruby-doc.org/core-2.1.4/Regexp.html


Or this:

str =~ /^[A-Z]+$/

e.g.:

"DOG" =~ /^[A-Z]+$/    # 0
"cat" =~ /^[A-Z]+$/    # nil 
0

精彩评论

暂无评论...
验证码 换一张
取 消