You are previewing Learning Ruby.

Learning Ruby

Cover of Learning Ruby by Michael Fitzgerald Published by O'Reilly Media, Inc.
  1. Learning Ruby
    1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
    2. A Note Regarding Supplemental Files
    3. Preface
      1. Who Should Read This Book?
      2. How This Book Works
      3. About the Examples
      4. How This Book Is Organized
      5. Conventions Used in This Book
      6. Comments and Questions
      7. Safari® Enabled
      8. Acknowledgments
    4. 1. Ruby Basics
      1. Hello, Matz
      2. Interactive Ruby
      3. Resources
      4. Installing Ruby
      5. Permission Denied
      6. Associating File Types on Windows
      7. Review Questions
    5. 2. A Quick Tour of Ruby
      1. Ruby Is Object-Oriented
      2. Ruby's Reserved Words
      4. Variables
      5. Strings
      6. Numbers and Operators
      7. Conditional Statements
      8. Arrays and Hashes
      9. Methods
      10. Blocks
      11. Symbols
      12. Exception Handling
      13. Ruby Documentation
      14. Review Questions
    6. 3. Conditional Love
      1. The if Statement
      2. The case Statement
      3. The while Loop
      4. The loop Method
      5. The for loop
      6. Execution Before or After a Program
      7. Review Questions
    7. 4. Strings
      1. Creating Strings
      2. Concatenating Strings
      3. Accessing Strings
      4. Comparing Strings
      5. Manipulating Strings
      6. Case Conversion
      7. Managing Whitespace, etc.
      8. Incrementing Strings
      9. Converting Strings
      10. Regular Expressions
      11. 1.9 and Beyond
      12. Review Questions
    8. 5. Math
      1. Class Hierarchy and Included Modules
      2. Converting Numbers
      3. Basic Math Operations
      4. Ranges
      5. Inquiring About Numbers
      6. More Math Methods
      7. Math Functions
      8. Rational Numbers
      9. Prime Numbers
      10. Review Questions
    9. 6. Arrays
      1. Creating Arrays
      2. Accessing Elements
      3. Concatenation
      4. Set Operations
      5. Unique Elements
      6. Blow Your Stack
      7. Comparing Arrays
      8. Changing Elements
      9. Deleting Elements
      10. Arrays and Blocks
      11. Sorting Things and About Face
      12. Multidimensional Arrays
      13. 1.9 and Beyond
      14. Other Array Methods
      15. Review Questions
    10. 7. Hashes
      1. Creating Hashes
      2. Accessing Hashes
      3. Iterating over Hashes
      4. Changing Hashes
      5. Converting Hashes to Other Classes
      6. 1.9 and Beyond
      7. Other Hash Methods
      8. Review Questions
    11. 8. Working with Files
      1. Directories
      2. Creating a New File
      3. Opening an Existing File
      4. Deleting and Renaming Files
      5. File Inquiries
      6. Changing File Modes and Owner
      7. The IO Class
      8. Review Questions
    12. 9. Classes
      1. Defining the Class
      2. Instance Variables
      3. Accessors
      4. Class Variables
      5. Class Methods
      6. Inheritance
      7. Modules
      8. public, private, or protected
      9. Review Questions
    13. 10. More Fun with Ruby
      1. Formatting Output with sprintf
      2. Processing XML
      3. Date and Time
      4. Reflection
      5. Using Tk
      6. Metaprogramming
      7. RubyGems
      8. Exception Handling
      9. Creating Documentation with RDoc
      10. Embedded Ruby
      11. Review Questions
    14. 11. A Short Guide to Ruby on Rails
      1. Where Did Rails Come From
      2. Why Rails?
      3. What Have Other Folks Done with Rails?
      4. Hosting Rails
      5. Installing Rails
      6. Learning Rails
      7. A Brief Tutorial
      8. Review Questions
    15. A. Ruby Reference
      1. Ruby Interpreter
      2. Ruby's Reserved Words
      3. Operators
      4. Escape Characters
      5. Predefined Variables
      6. Global Constants
      7. Regular Expressions
      8. String Unpack Directives
      9. Array Pack Directives
      10. Sprintf Flags and Field Types
      11. File Tests
      12. Time Formatting Directives
      13. RDoc Options
      14. Rake
    16. B. Answers to Review Questions
      1. Chapter 1 Review Questions
      2. Chapter 2 Review Questions
      3. Chapter 3 Review Questions
      4. Chapter 4 Review Questions
      5. Chapter 5 Review Questions
      6. Chapter 6 Review Questions
      7. Chapter 7 Review Questions
      8. Chapter 8 Review Questions
      9. Chapter 9 Review Questions
      10. Chapter 10 Review Questions
      11. Chapter 11 Review Questions
    17. Glossary
    18. Index
    19. About the Author
    20. Colophon
    21. SPECIAL OFFER: Upgrade this ebook with O’Reilly

Chapter 4. Strings

In the simplest terms, a string in a programming language is a sequence of one or more characters and usually represents some human language, whether written or spoken. You are probably more likely to use methods from the String class than from any other class in Ruby. Manipulating strings is one of the biggest chores a programmer has to manage. Fortunately, Ruby offers a lot of convenience in this department.

For more information on string methods, go to You can also use the command line to get information on a method. For example, to get information on the String instance method chop, type:

ri String#chop [or] ri String.chop

You can use # or . between the class and method names when returning two methods with ri. This, of course, assumes that you have the Ruby documentation package installed and that it is in the path (see "Installing Ruby," in Chapter 1).

Creating Strings

You can create strings with the new method. For example, this line creates a new, empty string called title:

title = # => ""

Now you have a new string, but it is only filled with virtual air. You can test a string to see if it is empty with empty?:

title.empty? # => true

You might want to test a string to see if it is empty before you process it, or to end processing when you run into an empty string. You can also test its length or size:

title.length [or] title.size # => 0

The length and size methods do the same thing: they both return an integer indicating how many characters a string holds.

The new method can take a string argument:

title = "Much Ado about Nothing" )

Now check title:

title.empty? # => false
title.length # => 22

There we go. Not quite so vacuous as before.

Another way to create a string is with Kernel's String method:

title = String( "Much Ado about Nothing" )
puts title # => Much Ado about Nothing

But there is an even easier way. You don't have to use the new or String methods to generate a new string. Just an assignment operator and a pair of double quotes will do fine:

sad_love_story = "Romeo and Juliet"

You can also use single quotes:

sad_love_story = 'Romeo and Juliet'

The difference between using double quotes versus single quotes is that double quotes interpret escaped characters and single quotes preserve them. I'll show you what that means. Here's what you get with double quotes (interprets \n as a newline):

lear = "King Lear\nA Tragedy\nby William Shakespeare"
puts lear # => King Lear
          #    A Tragedy
          #    by William Shakespeare

And here's what you get with single quotes (preserves \n in context):

lear = 'King Lear\nA Tragedy\nby William Shakespeare'
puts lear # => King Lear\nA Tragedy\nby William Shakespeare

For a complete list of escape characters, see Table A-1 in Appendix A.

General Delimited Strings

Another way to create strings is with general delimited strings, which are all preceded by a % and then followed by a matched pair of delimiter characters, such as !, {, or [ (must be nonalphanumeric). The string is embedded between the delimiters. All of the following examples are delimited by different characters (you can even use quote characters):

comedy = %!As You Like It!
history = %[Henry V]
tragedy = %(Julius Ceasar)

You can also use %Q, which is the equivalent of a double-quoted string; %q, which is equivalent to a single-quoted string; or %x for a back-quoted string (`) for command output.

Here Documents

A here document allows you to build strings from multiple lines on the fly, while preserving newlines. A here document is formed with a << and a delimiting character or string of your choice. I'll save Shakespeare's 29th sonnet as a here document, with 29 as the delimiter:

sonnet = <<29
When in disgrace with fortune and men's eyes
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself, and curse my fate,
Wishing me like to one more rich in hope,
Featured like him, like him with friends possessed,
Desiring this man's art, and that man's scope,
With what I most enjoy contented least;
Yet in these thoughts my self almost despising,
Haply I think on thee, and then my state,
Like to the lark at break of day arising
From sullen earth, sings hymns at heaven's gate;
For thy sweet love remembered such wealth brings
That then I scorn to change my state with kings.

This document is stored in the string sonnet, but you can create a here document without placing it in a string. Wherever the line breaks, a record separator (such as \n) is inserted at that place. Now use:

puts sonnet

You'll see for yourself how the lines break.

You can also "delimit the delimiter" for various effects:

sonnet = <<hamlet # same as double-quoted string
O my prophetic soul! My uncle!

sonnet = <<"hamlet" # again as double-quoted string
O my prophetic soul! My uncle!

sonnet = <<'ghost' # same as single-quoted string
Pity me not, but lend thy serious hearing
To what I shall unfold.

my_dir = <<`dir` # same as back ticks
ls -l

ind = <<-hello # for indentation
    Hello, Matz!

The best content for your career. Discover unlimited learning on demand for around $1/day.