Comparing and Manipulating Strings in Ruby (Page 1 of 4 )
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.
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