Wednesday, January 6, 2010

Section 4.3. Accessing Strings


Strings > Accessing Strings




4.3. Accessing Strings


You can extract and manipulate segments of a string using the String method []. It's an alias of the slice method: any place you use [], you can use slice, with the same arguments. slice! performs in-place changes and is a counterpart to []=.


We'll access several strings in the examples that follow:

line = "A horse! a horse! my kingdom for a horse!"
cite = "Act V, Scene IV"
speaker = "King Richard III"


If you enter a string as the argument to [], it will return that string, if found:

speaker['King'] # => "King"


Otherwise, it will return nil—in other words, it's trying to break the news to you: "I didn't find the string you were looking for." If you specify a Fixnum (integer) as an index, it returns the decimal character code for the character found at the index location:

line[7] # => 33


At the location 7, [] found the character 33 (!). If you add the chr method (from the Integer class), you'll get the actual character:

line[7].chr # => "!"


You can use an offset and length (two Fixnums) to tell [] the index location where you want to start, and then how many characters you want to retrieve:

line[18, 23] # => "my kingdom for a horse!"


You started at index location 18, and then scooped up 23 characters from there, inclusive. You can capitalize the result with the capitalize method, if you want:

line[18, 23].capitalize # => "My kingdom for a horse!"


(More on capitalize and other similar methods later in the chapter.)


Enter a range to grab a range of characters. Two dots (..) means include the last character:

cite[0..4] # => "Act V"


Three dots (...) means exclude the last value:

cite[0...4] # => "Act "


You can also use regular expressions (see the end of the chapter), as shown here:

line[/horse!$/] # => "horse!"


The regular expression /horse!$/ asks, "Does the word horse, followed by ! come at the end of the line ($)?" If this is true, this call returns horse!; nil if not. Adding another argument, a Fixnum, returns that portion of the matched data, starting at 0 in this instance:

line[/^A horse/, 0] # => "A horse"


The index method returns the index location of a matching substring. So if you use index like this:

line.index("k") # => 21


21 refers to the index location where the letter k occurs in line.


See if you get what is going on in the following examples:

line[line.index("k")] # => 107
line[line.index("k")].chr # => "k"


If you figured out these statements, you are starting to catch on! It doesn't take long, does it? If you didn't understand what happened, here it is: when line.index("k") was called, it returned the value 21, which was fed as a numeric argument to []; this, in effect, called line[21].


 

 


No comments: