Ruby: Multiline strings – Heredoc or quotes

There are various ways to define multi-line string in Ruby. The most important thing is, the DoubleQuoted construct supports the Interpolation.

a_multiline_string = %Q{ 
  The city is #{city}. 
  The temp is #{5.0/9.0 * (temp_f - 32)} C 
# Output
" \n  The city is Butwal. \n  The temp is 40.55555555555556 C \n"


 > name = "Shiva"
 => "Shiva" 
 > city = "Butwal"
 => "Butwal" 
 > multiline_string = <<-EOS
"> This is the first line
"> My name is #{name}.
"> My city is #{city} city.
"> EOS
 => "This is the first line\nMy name is Shiva.\nMy city is Butwal city.\n" 


 > multiline_string = <<EOS
"> First line
"> second line
"> third line
"> EOS
 => "First line\nsecond line\nthird line\n" 

the EOS in above example is just a convention, you can use any string you like and its case insensitive. Normally the EOS means End Of String

Moreover, even the - (dash) is not needed. However, allows you to indent the “end of here doc” delimiter. See the following example to understand the sentences.

 > <<EOF
"> My first line without dash
">         EOF
"> EOF
 => "My first line without dash\n        EOF\n" 

 > <<-EOF
"> My first line with dash. This even supports spaces before the ending delimiter.
">    EOF
 => "My first line without dash\n"  


 > multiline_string = %{
"> this is second line
"> this is third line
"> this is fourth line
"> }
 => "\nthis is second line\nthis is third line\nthis is fourth line\n"

Other alternatives

Also using array you can write multiline strings

 > lines = [
 >    'first line',
 >    'second line'
?>    ].join("\n")
 => "first line\nsecond line" 
 > puts lines
first line
second line


Special one is

   Specifying a timestamp name for #cache_key has been deprecated in favor of
   the explicit #cache_version method that can be overwritten.

squish will break the tradition and will let you close the parenthesis in the same line, while your string can span to multiple lines.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s