Home arrow Ruby-on-Rails arrow Page 5 - Iterating and Incrementing Strings in Ruby
RUBY-ON-RAILS

Iterating and Incrementing Strings in Ruby


In this conclusion to a three-part series focusing on strings in Ruby, you will learn not only how to iterate over and increment a string, but how to manage whitespace, convert a string, and more. It is excerpted from chapter four of Learning Ruby, written by Michael Fitzgerald (O'Reilly; 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 21, 2008
TABLE OF CONTENTS:
  1. · Iterating and Incrementing Strings in Ruby
  2. · Iterating Over a String
  3. · Managing Whitespace, etc.
  4. · Incrementing Strings
  5. · Converting Strings
  6. · Regular Expressions

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
Iterating and Incrementing Strings in Ruby - Converting Strings
(Page 5 of 6 )

You can convert a string into a float (Float) or integer (Fixnum). To convert a string into a float, or, more precisely, an instance of the Stringclass into an instance ofFloat, use theto_fmethod:

  "200".class # => String
  "200".to_f # => 200.0
  "200".to_f.class # => Float

Likewise, to convert a string to an integer, useto_i:

  "100".class # => String
 
"100".to_i # => 100
 
"100".to_i.class # => Fixnum

To convert a string into a symbol (Symbolclass), you can use either theto_symorinternmethods.

  "name".intern # => :name
 
"name".to_sym # => :name

The value of the string, not its name, becomes the symbol:

  play = "The Merchant of Venice".intern # => :"The Merchant of Venice"

Convert an object to a string withto_s. Ruby calls theto_smethod from the class of the object, not theStringclass (parentheses are optional).

  (256.0).class # => Float
 
(256.0).to_s # => "256.0"


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 1 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials