Home > Back-end >  How to avoid string interpolation in Ruby HEREDOC multi line string
How to avoid string interpolation in Ruby HEREDOC multi line string

Time:12-22

I have a multi line HEREDOC such as this:

c = <<-MYTEXT
{ 'Cache-Control' => "public, max-age=#{2.days.to_i}" }
MYTEXT

This raises the error

undefined method `days' for 2:Integer (NoMethodError)

I don't want Ruby to interpolate the string and write the value of 2 days in integer, but instead I want it to write exactly the string #{2.days.to_i}

If I escape the # and the \ write it like

{ 'Cache-Control' => "public, max-age=\#\{2.days.to_i\}\" }

it works, but imagine a long text with many #{} string interpolations, ugly.

Any smarter way of doing this?

CodePudding user response:

You can "disable" interpolation by using single-quoted strings

c = <<-'MYTEXT'
{ 'Cache-Control' => "public, max-age=#{2.days.to_i}" }
MYTEXT
  •  Tags:  
  • ruby
  • Related