Sahil Dhankhar
Sahil Dhankhar

Reputation: 3656

Ruby determining whether a letter is uppercase or not

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?

Upvotes: 5

Views: 4865

Answers (7)

Stefan
Stefan

Reputation: 114188

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

Upvotes: 8

AgentIvan
AgentIvan

Reputation: 30

There are several ways to check if the character is uppercase

# false
c = 'c'
p c=~/[A-Z]/
p c==c.upcase
p /[A-Z]/===c
p (?A..?Z)===c
p ?A<=c&&c<=?Z
p (?A..?Z).cover?c
p c=~/[[:upper:]]/
p /[[:upper:]]/===c

# true
C = 'C'
p C=~/[A-Z]/
p C==C.upcase
p /[A-Z]/===C
p (?A..?Z)===C
p ?A<=C&&C<=?Z
p (?A..?Z).cover?C
p C=~/[[:upper:]]/
p /[[:upper:]]/===C

=~ returns a nil or 0.

!!nil == false; !!0 == true.

P.S. Not all of them works in the same way

  • '.' == '.'.upcase => true but it's not a capital letter
  • If you need to check letters with diphthongs use /[[:upper:]]/==='Ñ' => true as expected
  • In this case you can to add interested letters manually: /[A-ZÑ]/==='Ñ' => true

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110685

x >= 'A' && x <= 'Z'

Upvotes: 1

Matt
Matt

Reputation: 20786

'A' =~ /[A-Z]/ #=> 0 (boolean true)
'a' =~ /[A-Z]/ #=> nil (boolean false)

Upvotes: 2

hirolau
hirolau

Reputation: 13911

def is_upcase? x 
  ('A'..'Z').cover? x
end

Edit: .cover? is a new function in 1.9 that checks if value is in range by only checking the endpoints. In that way the computer does not need to convert it into an array and store it in memory, making it faster.

It is basically another way of writing x >= 'A' && x <= 'Z'

Upvotes: 1

spickermann
spickermann

Reputation: 106932

Also lacks support for umlauts, diacritcs etc. und needs ActiveSupport, but I like the syntax:

'A'.in?('A'..'Z')  # => true
'a'.in?('A'..'Z')  # => false

Upvotes: 2

Ray Toal
Ray Toal

Reputation: 88388

Use ===

?> ('A'..'Z') === 'C'
=> true
>> ('A'..'Z') === 'c'
=> false
>> ('A'..'Z') === '1'
=> false
>> ('A'..'Z') === '&'
=> false
>> ('A'..'Z') === 'Z'
=> true

Upvotes: 2

Related Questions