RubyA Diamond of a Programming Language, Part 2 : Page 2

Get ready to dive deeper into the power and elegance of the language lauded as a possible contender to replace current programming languages.

by Jim White

Apr 10, 2006

Page 2 of 8

Strings
Strings are arbitrary sequence of bytes in Ruby. Usually they are a sequence of characters. In Ruby, instances of the String class can be created using a literal or the new method on the String class.

Of course, the String defines a great many methods (and operators) for string instances. Also, strings can either be specified with single or double quotes. Double quotes allow for many escape characters and embedded expressions to be evaluated and used in the strings. With single quoted strings, what you see is what you get. For a better understanding, look at the following examples.

Notice how text inside of double quotes is evaluated before displaying where character escapes (like \n) and expressions (like #{2+2}) included. On the other hand, these items are treated literally in single quoted strings?

Besides the single and double quote characters to denote a string literal, there is another way to write string literals in Ruby. A percent sign and lowercase or uppercase letter Q can be used to write a string in either single-quote or double-quote style respectively.

Note that the character following q% or Q% defines the beginning and end of the string literal. The @ symbol is used in this example as the delimiter marking the beginning and ending of the string.

It should be noted for those that come from other programming language backgrounds that Ruby does not differentiate between a string and character. In other words, there is no special class for single characters, they are just small strings.

Boolean
Lastly, before leaving the "standard" types arena, let's look at Booleans. In Ruby, there are two classes for Boolean: TrueClass and FalseClass. There is only one instance (a singleton) for each of these classes; namely true and false. These are global values accessible anywhere in Ruby. There is also a class called the NilClass. NilClass also has only one instancenil. Nil represents…well, nothing. In the case of Boolean logic, however, nil is synonymous with false.