# Changing the Case of a String

Problem

Your string is in the wrong case, or no particular case at all.

Solution

The String class provides a variety of case-shifting methods:

```	s = 'HELLO, I am not here. I WENT to tHe MaRKEt.'
s.
upcase # => "HELLO, I AM NOT HERE. I WENT TO THE MARKET."
s.
downcase # => "hello, i am not here. i went to the market."
s.swapcase # => "hello, i AM NOT HERE. i went TO ThE mArkeT."
s.capitalize # => "Hello, i am not here. i went to the market."
```

Discussion

The upcase and downcase methods force all letters in the string to upper-or lowercase, respectively. The swapcase method transforms uppercase letters into lowercase letters and vice versa. The capitalize method makes the first character of the string uppercase, if it's a letter, and makes all other letters in the string lowercase.

All four methods have corresponding methods that modify a string in place rather than creating a new one: upcase!, downcase!, swapcase!, and capitalize!. Assuming you don't need the original string, these methods will save memory, especially if the string is large.

```	un_banged = 'Hello world.'
un_banged.upcase # => "HELLO WORLD."
un_banged # => "Hello world."

banged = 'Hello world.'
banged.upcase! # => "HELLO WORLD."
banged # => "HELLO WORLD."
```

To capitalize a string without lowercasing the rest of the string (for instance, because the string contains proper nouns), you can modify the first character of the string in place. This corresponds to the capitalize! method. If you want something more like capitalize, you can create a new string out of the old one.

```	class String
def capitalize_first_letter
self[0].chr.capitalize + self[1, size]
end

def capitalize_first_letter!
unless self[0] == (c = self[0,1].upcase[0])
self[0] = c
self
end
# Return nil if no change was made, like upcase! et al.
end
end

s = 'i told Alice. She remembers now.'
s.capitalize_first_letter # => "I told Alice. She remembers now."
s # => "i told Alice. She remembers now."
s.capitalize_first_letter!
s # => "I told Alice. She remembers now."
```

To change the case of specific letters while leaving the rest alone, you can use the TR or TR! methods, which translate one character into another:

```	'LOWERCASE ALL VOWELS'.tr('AEIOU', 'aeiou')
# => "LoWeRCaSe aLL VoWeLS"

'Swap case of ALL VOWELS'.tr('AEIOUaeiou', 'aeiouAEIOU')
# => "SwAp cAsE Of aLL VoWeLS"
```

• Recipe 1.18, "Replacing Multiple Patterns in a Single Pass"
• The Facets Core library adds a String#camelcase method; it also defines the case predicates String#lowercase? and String#uppercase?

Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399