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"

Moreover,

 > 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" 

or

 > 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"  

also

 > 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

 ActiveSupport::Deprecation.warn(<<-MSG.squish)
   Specifying a timestamp name for #cache_key has been deprecated in favor of
   the explicit #cache_version method that can be overwritten.
 MSG

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

One thought on “Ruby: Multiline strings – Heredoc or quotes

Leave a comment