Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Page 4 - Strings in Ruby
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
RUBY-ON-RAILS

Strings in Ruby
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2008-08-07

    Table of Contents:
  • Strings in Ruby
  • General Delimited Strings
  • Concatenating Strings
  • Accessing Strings

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    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.

       · This article is an excerpt from the book "Learning Ruby," published by O'Reilly. We...
     

    Buy this book now. 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.

    RUBY-ON-RAILS ARTICLES

    - Iterating and Incrementing Strings in Ruby
    - Comparing and Manipulating Strings in Ruby
    - Strings in Ruby
    - Ruby On Rails: Making Your First Dynamic Site
    - Ruby on Rails: Beginning Rails
    - Ruby: Modules, Mixins, Fixins, and Rails
    - Controlling Information Access with the Rail...
    - URLs, Filters and the Rails Action Controller
    - Flash and the Rails Action Controller
    - Rails Action Controller
    - Dropping and Sorting with AJAX and script.ac...
    - Drag and Drop with script.aculo.us and Rails
    - Introducing script.aculo.us
    - Ruby Classes and Objects
    - Ruby Loops







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek