Changes

Ruby String Concatenation and Comparison

904 bytes added, 21:06, 27 November 2007
Accessing String Elements
myString.index("Ruby")
=> 11
</pre>
 
== Comparing Ruby Strings ==
 
It is not uncommon to need to compare two strings, either to assess equality or to find out if one string is higher or lower than the other (alphabetically speaking).
 
Equality is performed either using the == or ''eql?'' methods:
 
<pre>
"John" == "Fred"
=> false
 
"John".eql? "John"
=> true
</pre>
 
The spaceship (<=>) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method return 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:
 
<pre>
"Apples" <=> "Apples"
=> 0
 
 
"Apples" <=> "Pears"
=> -1
 
"Pears" <=> "Apples"
=> 1
</pre>
 
== Case Insensitive String Comparisons ==
 
A case insensitive comparison may be performed using the ''casecmp'' method which returns the same values as the <=> method described above:
 
<pre>
"Apples".casecmp "apples"
=> 0
</pre>