Tuesday 30 August 2011

Ruby: strings

Single-quoted strings only support two escape sequences: two consecutive backslashes are replaced by a single backslash, and a backslash followed by a single quote becomes a single quote.

Double-quoted strings support more escape sequences, like "\n". It also allows string interpolation #{expr}. If the code is just a global variable, a class variable, or an instance variable, you can omit the braces.

%q and %Q start delimited single- and double-quoted strings as well.
%q/general single-quoted string/
%Q!general double-quoted sting!
%{Seconds/day: #{24 * 60 * 60}} # => Q can be ommitted.


You can also construct a string using a here document:
string = <<END_OF_STRING
    The body of the string
    is the input lines up to 
    one starting with the same
    text that followed the '<<'
END_OF_STRING

Normally, the terminator of the here document must start in the first column. However if you put a minus sign after the << characters, you can indent the terminator:
string = <<-END_OF_STRING
    The body of the string
    is the input lines up to 
    one starting with the same
    text that followed the '<<'
    END_OF_STRING

To initialize an array of strings, you can use %w:
%w(foo bar) # => ["foo", "bar"]

No comments :

Post a Comment