Ruby String Conversions
So far we have looked at creating, comparing and manipulating strings. Now it is time to look at converting strings in Ruby.
Converting a Ruby String to an Array
Strings can be converted to arrays using a combination of the split method and some regular expressions. The split methods serves to break up the string into distinct parts which can be placed into array element. The regular expression tells split what to use as the break point during the conversion process.
We can start by converting an entire string into an array with just one element (i.e the entire string):
myArray = "ABCDEFGHIJKLMNOP".split => ["ABCDEFGHIJKLMNOP"]
This has created an array object called myArray. Unfortunately this isn't much use to use because we wanted each character in our string to be placed in a individual array element. To do this we need to specify a regular expression. In this case we need to use the regular expression which represents the point between two characters (//) and pass it through as an argument to the split method:
myArray = "ABCDEFGHIJKLMNOP".split(//) => ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"]
We can also create an array based on words by using the space (/ /) as the break point:
myArray = "Paris in the Spring".split(/ /) => ["Paris", "in", "the", "Spring"]
Or we can even, perhaps most usefully, convert a comma separated string into an array:
myArray = "Red, Green, Blue, Indigo, Violet".split(/, /) => ["Red", "Green", "Blue", "Indigo", "Violet"]
Changing the Case of a Ruby String
The first letter of a string (and only the first letter of a string) can be capitalized using the capitalize and capitalize! methods (the returns a modified string, the second changes the original string):
"paris in the spring".capitalize => "Paris in the spring"
The first character of each word in a Ruby string may be capitalized by iterating through the string (assuming the record separator is a new line):
"one\ntwo\nthree".each {|word| puts word.capitalize} One Two Three => "one\ntwo\nthree"
The case of every character in a string may be converted using the upcase, downcase and swapcase methods. These methods are somewhat self explanatory, but here are some examples for the avoidance of doubt:
"PLEASE DON'T SHOUT!".downcase => "please don't shout!" "speak up. i can't here you!".upcase => "SPEAK UP. I CAN'T HERE YOU!" "What the Capital And Lower Case Letters Swap".swapcase => "wHAT THE cAPITAL aND lOWER cASE lETTERS sWAP"