Changes

Jump to: navigation, search

Ruby String Replacement, Substitution and Insertion

1,717 bytes added, 17:54, 28 November 2007
Inserting Text Into a Ruby String
== Inserting Text Into a Ruby String ==
 
So far in this chapter we have looked exclusively at changing the existing text contained in a Ruby string object. Another common requirement is to insert new text at a certain location in a string. This is achieved in Ruby using the ''insert'' method. The insert method takes as arguments index postion into the string where the insertion is take place, followed by the string to be inserted
 
<pre>
myString = "Paris in Spring"
 
myString.insert 8, " the"
=> "Paris in the Spring"
</pre>
 
== Ruby chomp and chop Methods ==
 
The purpose of the ''chop'' method is to remove the trailing character from a string:
 
<pre>
myString = "Paris in the Spring!"
=> "Paris in the Spring!"
 
myString.chop
=> "Paris in the Spring"
</pre>
 
Note that ''chop'' returns a modified string, leaving the original string object unchanged. Use ''chop!'' to have the change applied to the string object on which the method was called.
 
The ''chomp'' method removes ''record separators'' from a string. The record separator is defined by the $/ variable and is, by default, the new line character (\n). As with the ''chop'' method the ''chomp!'' variant of the method applies the change to string object on which the method is called:
 
<pre>
myString = "Please keep\n off the\n grass"
=> "Please keep\n off the\n grass\n"
 
myString.chomp!
=> "Please keep\n off the\n grass"
</pre>
 
== Reversing the Characters in a String ==
 
The ''reverse'' method is used to reverse the contents of a string:
 
<pre>
myString = "Paris in the Spring"
=> "Paris in the Spring"
 
myString.reverse
=> "gnirpS eht ni siraP"
</pre>
 
Once again, not something I've ever needed to do in all my years as a developer, but you never know when you might need to do it.

Navigation menu