Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. Strings > Comparing Strings

4.4. 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 is false, because they must match exactly. (We'll let the historians figure out how to match them up.) You could also apply the eql? method and get the same results, though eql? and == are slightly different:

  • == returns true if two objects are Strings, false otherwise.

  • eql? returns true if two strings are equal in length and content, false otherwise.

Here eql? 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), or 1 (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 with casecmp, 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