Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

2.11 Controlling Uppercase and Lowercase

Ruby’s String class offers a rich set of methods for controlling case. This section offers an overview of these.

The downcase method converts a string to all lowercase. Likewise, upcase converts it to all uppercase. Here is an example each:

s1 = "Boston Tea Party"
s2 = s1.downcase             # "boston tea party"
s3 = s2.upcase               # "BOSTON TEA PARTY"

The capitalize method capitalizes the first character of a string while forcing all the remaining characters to lowercase:

s4 = s1.capitalize           # "Boston tea party"
s5 = s2.capitalize           # "Boston tea party"
s6 = s3.capitalize           # "Boston tea party"

The swapcase method exchanges the case of each letter in a string:

s7 = "THIS IS AN ex-parrot."
s8 = s7.swapcase             # "this is an EX-PARROT."

There is also the casecmp method, which acts like the <=> method but ignores case:

n1 = "abc".casecmp("xyz")    # -1
n2 = "abc".casecmp("XYZ")    # -1
n3 = "ABC".casecmp("xyz")    # -1
n4 = "ABC".casecmp("abc")    # 0
n5 = "xyz".casecmp("abc")    # 1

Each of these also has an in-place equivalent (upcase!, downcase!, capitalize!, and swapcase!).

There are no built-in methods for detecting case, but this is easy to do with regular expressions, as shown in the following example:

if string =~ /[a-z]/
  puts "string contains lowercase characters"

if string =~ /[A-Z]/
  puts "string contains uppercase characters"

if string =~ /[A-Z]/ and string =~ /a-z/
  puts "string contains mixed case"

if string[0..0] =~ /[A-Z]/
  puts "string starts with a capital letter"

Regular expressions of this sort will only match ASCII characters. To match Unicode uppercase or lowercase characters, use a named character class, as shown here:

if string =~ /\p{Upper}/
  puts "string contains uppercase Unicode characters like Ü"

For more information about regular expressions, see Chapter 3, “Working with Regular Expressions.”

  • + Share This
  • 🔖 Save To Your Account