Home arrow Ruby-on-Rails arrow Page 4 - Strings in Ruby
RUBY-ON-RAILS

Strings in Ruby


Strings are used in every programming language, and most programmers spend a lot of time manipulating strings. This article will explain the various ways you can use and manipulate strings in Ruby. It is excerpted from chapter four of Learning Ruby, written by Michael Fitzgerald (O'Reilly, 2007; ISBN: 0596529864). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 3
August 07, 2008
TABLE OF CONTENTS:
  1. · Strings in Ruby
  2. · General Delimited Strings
  3. · Concatenating Strings
  4. · Accessing Strings

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
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.

blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form
- Ruby on Rails Templates and Layouts
- Action Pack Controller Creation
- Writing an Action Pack Controller

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 4 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials