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?
You can use POSIX character classes:
/[[:lower:]]/
- Lowercase alphabetical character/[[:upper:]]/
- Uppercase alphabeticalExample:
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
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