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" - with a capital "S" in the end if the word is plural (vs. "WORDs").
Thanks!
To check if a string is all uppercase, use the toUppercase() method to convert the string to uppercase and compare it to itself. If the comparison returns true , then the string is all uppercase.
Symbol#upcase() : upcase() is a Symbol class method which returns the uppercase representation of the symbol object. Return: the uppercase representation of the symbol object.
capitalize is a String class method in Ruby which is used to return a copy of the given string by converting its first character uppercase and the remaining to lowercase. Parameters: Here, str is the given string which is to be converted.
Look into the String#capitalize method. String#capitalize downcases the rest of the string after the first letter.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With