Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

Ruby Programming
Previous Page Home Next Page

Pattern-Based Substitution

Sometimes finding a pattern in a string is good enough. If a friend challenges you to find a word that contains the letters a, b, c, d, and e in order, you could search a word list with the pattern /a.*b.*c.*d.*e/ and find ``absconded'' and ``ambuscade.'' That has to be worth something.

However, there are times when you need to change things based on a pattern match. Let's go back to our song list file. Whoever created it entered all the artists' names in lowercase. When we display them on our jukebox's screen, they'd look better in mixed case. How can we change the first character of each word to uppercase?

The methods String#sub and String#gsub look for a portion of a string matching their first argument and replace it with their second argument. String#sub performs one replacement, while String#gsub replaces every occurrence of the match. Both routines return a new copy of the String containing the substitutions. Mutator versions String#sub! and String#gsub! modify the original string.

a = "the quick brown fox"
a.sub(/[aeiou]/,  '*') "th* quick brown fox"
a.gsub(/[aeiou]/, '*') "th* q**ck br*wn f*x"
a.sub(/\s\S+/,  '') "the brown fox"
a.gsub(/\s\S+/, '') "the"

The second argument to both functions can be either a String or a block. If a block is used, the block's value is substituted into the String.

a = "the quick brown fox"
a.sub(/^./) { $&.upcase } "The quick brown fox"
a.gsub(/[aeiou]/) { $&.upcase } "thE qUIck brOwn fOx"

So, this looks like the answer to converting our artists' names. The pattern that matches the first character of a word is \b\w---look for a word boundary followed by a word character. Combine this with gsub and we can hack the artists' names.

def mixedCase(aName)
  aName.gsub(/\b\w/) { $&.upcase }
end
mixedCase("fats waller") "Fats Waller"
mixedCase("louis armstrong") "Louis Armstrong"
mixedCase("strength in numbers") "Strength In Numbers"

Ruby Programming
Previous Page Home Next Page

 
 
  Published under the terms of the Open Publication License Design by Interspire