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 http://www.ruby-doc.org/core/classes/String.html. You can also use the command line to get information on a method. For example, to get information on theStringinstance methodchop, 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 Chapter1 ).
You can create strings with the newmethod. For example, this line creates a new, empty string calledtitle:
title = String.new # => ""
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 withempty?:
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
Thelengthandsizemethods do the same thing: they both return an integer indicating how many characters a string holds.
Thenewmethod can take a string argument:
title = String.new( "Much Ado about Nothing" )
title.empty? # => false title.length # => 22
There we go. Not quite so vacuous as before.
Another way to create a string is withKernel’sString 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 theneworStringmethods 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\nas 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\nin context):
lear = 'King Lear\nA Tragedy\nby William Shakespeare' puts lear # => King Lear\nA Tragedy\nby William Shakespeare