Changes

Ruby String Concatenation and Comparison

1,045 bytes added, 20:55, 27 November 2007
Freezing a Ruby String
myString << "hello"
TypeError: can't modify frozen string
</pre>
 
== Accessing String Elements ==
 
Fragments of a Ruby string can be accessed using the [] method of the ''String class''. One use for this method is to find if a particular sequence of characters exists in a string. If a match is found the sequence is returned, otherwise ''nil'' is returned:
 
<pre>
myString = "Welcome to Ruby!"
 
myString["Ruby"]
=> "Ruby"
 
myString["Perl"]
=> nil
</pre>
 
Pass an integer through to the [] method and the ASCII code of the character at that location in the string (starting at zero) will be returned. This can be converted back to a character using the ''chr'' method:
 
<pre>
myString[3].chr
=> "c"
</pre>
 
You can also pass through a start position and a number of characters to extract a subsection of a string:
 
<pre>
myString[11, 4]
=> "Ruby"
</pre>
 
You can also use a Range to specify a group of characters between start and end points:
 
<pre>
myString[0..6]
=> "Welcome"
</pre>
 
The location of a matching substring can be obtained using the ''index'' method:
 
<pre>
myString.index("Ruby")
=> 11
</pre>