Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is all-capitals in Rails

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!

like image 835
Yuval Karmi Avatar asked Feb 28 '10 05:02

Yuval Karmi


People also ask

How do you check if a string is all capital?

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.

Does Ruby have Upcase?

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.

Is capitalized Ruby?

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.

How do you capitalize all words in a string in Ruby?

Look into the String#capitalize method. String#capitalize downcases the rest of the string after the first letter.


3 Answers

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
like image 50
Harish Shetty Avatar answered Oct 19 '22 06:10

Harish Shetty


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

like image 28
skalee Avatar answered Oct 19 '22 04:10

skalee


Or this:

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

e.g.:

"DOG" =~ /^[A-Z]+$/    # 0
"cat" =~ /^[A-Z]+$/    # nil 
like image 2
James A. Rosen Avatar answered Oct 19 '22 04:10

James A. Rosen