Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby determining whether a letter is uppercase or not

Tags:

ruby

The question is very simple and probably have thousand of answers, but i am looking for some magical ruby function.

Problem: To determine whether a letter is upcase or not i.e belongs to A-Z.

Possible Solution:

array = ["A","B", ....., "Z"]
letter = "A"
is_upcase = array.include? letter

Please note that "1" is not an uppercase letter.

Is there any magical ruby function which solve the problem with less code?

like image 442
Sahil Dhankhar Avatar asked Dec 08 '22 11:12

Sahil Dhankhar


1 Answers

You can use POSIX character classes:

  • /[[:lower:]]/ - Lowercase alphabetical character
  • /[[:upper:]]/ - Uppercase alphabetical

Example:

def which_case(letter)
  case letter
  when /[[:upper:]]/
    :uppercase
  when /[[:lower:]]/
    :lowercase
  else
    :other
  end
end

which_case('a') #=> :lowercase
which_case('ä') #=> :lowercase
which_case('A') #=> :uppercase
which_case('Ä') #=> :uppercase
which_case('1') #=> :other

Or with a simple if statement:

puts 'lowercase' if /[[:lower:]]/ =~ 'a'
#=> lowercase
like image 173
Stefan Avatar answered Dec 11 '22 08:12

Stefan