views:

267

answers:

2

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!

+12  A: 

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
KandadaBoggu
thank you! that works :)
yuval
+1  A: 

Or this:

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

e.g.:

"DOG" =~ /^[A-Z]+$/    # 0
"cat" =~ /^[A-Z]+$/    # nil 
James A. Rosen
Does not work when string has anything else than A-Z in it. DÖG or CÄT or DOG123 for example.
Priit
Quite true. If internationalization is an issue, the `str == str.upcase` might work better, but that depends on the definition of `upcase`. On my system, `"coöperation".upcase` is `"COöPERATION"`, which doesn't really help. Ruby 1.9 is more encoding-aware; for those on 1.8, there's the Unicode gem: http://rubygems.org/gems/unicode
James A. Rosen