Strings in Ruby - Accessing Strings
(Page 4 of 4 )
You can extract and manipulate segments of a string using the String method[]. It’s an alias of theslicemethod: any place you use[], you can useslice, 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 returnnil—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 aFixnum(integer) as an index, it returns the decimal character code for the character found at the index location:
line[7] # => 33
At the location7,[]found the character33(!). If you add thechrmethod (from theIntegerclass), you’ll get the actual character:
line[7].chr # => "!"
You can use an offset and length (twoFixnums) 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 thecapitalizemethod, if you want:
line[18, 23].capitalize # => "My kingdom for a horse!"
(More oncapitalizeand 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 wordhorse, followed by!come at the end of the line ($)?” If this is true, this call returnshorse!;nilif not. Adding another argument, aFixnum, returns that portion of the matched data, starting at0in this instance:
line[/^A horse/, 0] # => "A horse"
Theindexmethod returns the index location of a matching substring. So if you useindexlike this:
line.index("k") # => 21
21 refers to the index location where the letterkoccurs inline.
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 value21, which was fed as a numeric argument to[]; this, in effect, calledline[21].
Please check back next week for the continuation of this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article is excerpted from chapter four of Learning Ruby, written by Michael Fitzgerald (O'Reilly, 2007; ISBN: 0596529864). Check it out today at your favorite bookstore. Buy this book now.
|
|