I'm ashamed to ask this, because it seems like it ought to be obvious, but how does one tell whether a given character in a string is upper or lowercase in Ruby? I see no obvious canned solution in the String
class.
I've resorted to the following, which does not consider non-ASCII codes:
def is_lower?(c)
c >= 'a' && c <= 'z'
end
def is_upper?(c)
! is_lower(c)
end
Something else I've considered is:
def is_lower?(c)
c != c.upcase
end
Is there something more idiomatic for this?
Use a regex pattern: [A-Z] or:
/[[:upper:]]/.match(c)
I don't think there is something more idiomatic. The only thing you could do -- instead of passing in the string as an argument -- is monkey patch the String
class:
class String
def is_upper?
self == self.upcase
end
def is_lower?
self == self.downcase
end
end
"a".is_upper? #=> false
"A".is_upper? #=> true
Using the method in the answer suggested by the commenter above and monkey patching String
, you could do this:
class String
def is_upper?
!!self.match(/\p{Upper}/)
end
def is_lower?
!!self.match(/\p{Lower}/)
# or: !self.is_upper?
end
end
What does it mean for a string to be lower case? Does it mean that the string only contains lower case characters or that it doesn't contain any upper case characters? In my case I want:
"a2".is_lower? #=> true
..which leads me to:
class String
def is_upper?
not self.match /[[:lower:]]/
end
def is_lower?
not self.match /[[:upper:]]/
end
end
Note that /\p{Lower}/
might be better but is unsupported on Ruby 1.8.
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