Archive for September 17th, 2010

Ruby String Concatenation and Comparison – Techotopia

Ruby String Concatenation and Comparison – Techotopia.

Concatenating Strings in Ruby

If you’ve read any of the preceding chapters in this book you will have noticed that Ruby typically provides a number of different ways to achieve the same thing. Concatenating strings is certainly no exception to this rule.

Strings can be concatenated using the + method:

myString = "Welcome " + "to " + "Ruby!"
=> "Welcome to Ruby!"

In the interests of brevity, you can even omit the + signs:

myString = "Welcome " "to " "Ruby!"
=> "Welcome to Ruby!"

If you aren’t happy with the above options you can chain strings together using the << method:

myString = "Welcome " << "to " << "Ruby!"
=> "Welcome to Ruby!"

Still not enough choices for you? Well, how about using the concat method:

myString = "Welcome ".concat("to ").concat("Ruby!")
=> "Welcome to Ruby!"

Freezing a Ruby String

A string can be frozen after it has been created such that it cannot subsequently be altered. This is achieved using the freeze method of the String class:

myString = "Welcome " << "to " << "Ruby!"
=> "Welcome to Ruby!"


myString << "hello"
TypeError: can't modify frozen string

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:

myString = "Welcome to Ruby!"

=> "Ruby"

=> nil

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:

=> "c"

You can also pass through a start position and a number of characters to extract a subsection of a string:

myString[11, 4]
=> "Ruby"

You can also use a Range to specify a group of characters between start and end points:

=> "Welcome"

The location of a matching substring can be obtained using the index method:

=> 11

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:

"John" == "Fred"
=> false

"John".eql? "John"
=> true

The spaceship (<=>) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 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:

"Apples" <=> "Apples"
=> 0

"Apples" <=> "Pears"
=> -1

"Pears" <=> "Apples"
=> 1

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:

"Apples".casecmp "apples"
=> 0