Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: how to tell if character is upper/lowercase

Tags:

ruby

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?

like image 402
George Armhold Avatar asked Oct 03 '12 16:10

George Armhold


3 Answers

Use a regex pattern: [A-Z] or:

/[[:upper:]]/.match(c)
like image 68
sfell77 Avatar answered Nov 19 '22 10:11

sfell77


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
like image 33
Mischa Avatar answered Nov 19 '22 09:11

Mischa


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.

like image 7
Neil Stockbridge Avatar answered Nov 19 '22 09:11

Neil Stockbridge