Comparing and Manipulating Strings in Ruby
(Page 1 of 4 )
In this second part of a three-part series focusing on strings in Ruby, you will learn how to test two strings to see if they are the same, 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.
Comparing Strings
Sometimes you need to test two strings to see if they are the same or not. You can do that with the == method. For example, you might want to test a string before printing something:
print "What was the question again?" if question == ""
Also, here are two versions of the opening paragraph of Abraham Lincoln’s Gettysburg Address, one from the so-called Hay manuscript, the other from the Nicolay (see http://www.loc.gov/exhibits/gadd/gadrft.html):
hay = "Four score and seven years ago our fathers brought forth, upon this continent,
a new nation, conceived in Liberty, and dedicated to the proposition that all men are
created equal."
nicolay = "Four score and seven years ago our fathers brought forth, upon this
continent, a new nation, conceived in liberty, and dedicated to the proposition that
"all men are created equal""
The strings are only slightly different (for example, Liberty is capitalized in the Hay version). Let’s compare these strings:
hay == nicolay # => false
The result isfalse, because they must match exactly. (We’ll let the historians figure out how to match them up.) You could also apply theeql?method and get the same results, thougheql?and==are slightly different:
- ==returns true if two objects areStrings, false otherwise.
- eql?returns true if two strings are equal in length and content, false otherwise.
Hereeql?returns false:
hay.eql? nicolay # => false
Yet another way to compare strings is with the<=>method, commonly called the spaceship operator. It compares the character code values of the strings, returning-1(less than),0(equals), or1(greater than), depending on the comparison, which is case-sensitive:
"a" <=> "a" # =>0
"a" <=> 97.chr # => 0
"a" <=> "b" # => -1
"a" <=> "`" # => 1
A case-insensitive comparison is possible withcasecmp, which has the same possible results as<=> (-1,0,1) but doesn’t care about case:
"a" <=> "A" # => 1
"a".casecmp "A" # => 0
"ferlin husky".casecmp "Ferlin Husky" # => 0
"Ferlin Husky".casecmp "Lefty Frizzell" # => -1
Next: Manipulating Strings >>
More Ruby-on-Rails Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of Learning Ruby, written by Michael Fitzgerald (O'Reilly; ISBN: 0596529864). Check it out today at your favorite bookstore. Buy this book now.
|
|