Defining a string in Ruby is pretty simple:
s1 = 'Hello!' s2 = "This is a string.\n Calculations: 2+2=#{2+2}"
You can use both single and double quotes, however double quotes give you much more – expressions enclosed in #{} would be processed by Ruby before string is shown. Pretty cool, heh?
But I am sure most of you have already known that. Let’s proceed than: consider you have a string, that contains many mixed quotes (‚) and double quotes („). How to write it, if the same marks (‚) and („) are considered as string delimiters? Of course you can concatenate string step by step delimiting single quote with double quoted and vice versa, but this is painful. There is a better solution:
Custom string delimiters
Ruby provides a mechanism to define custom string delimiter both as single quoted %q and double quoted %Q string alternative. Let’s see examples:
s3 = %q[My dog's name is George "Jonny" the Second] #single quoted string s4 = %Q/One can define a string by s = "String content" or s2 = 'string2 content'\n Calculations: 2+2=#{2+2}/
So as string delimiters one can use a nonalphanumeric character that should go right after %q or %Q and the string should be terminated with the same character. In case you use brackets, you should terminate the string with the corresponding closing bracket.
Operating system commands
Strings enclosed with backquotes or %x{} would be considered by Ruby as operating system commands. Just try:
puts (`calc`)
or
puts ("Current directory content is: #{%x/dir/}")
HEREDOCS
The last, but not least neat way to define long, multiline strings is so called HEREDOCS. Let’s see an example first:
LongString = <<LINEEND Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the #{15*100}s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. LINEEND
The HEREDOCs string starts with specifying the end marker (in my example: LINEEND). Everything you write would be treated as doublequoted string till you write the end marker (should be placed nonindendet in a new line).