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 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 the String instance method chop,
type:
ri String#chop [or] ri String.chopYou 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 = 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 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 # => 0The length and size methods do the same thing: they both return an ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access