Question

I have a heredoc where I am using #{} to interpolate some other strings, but there is an instance where I also want to write the actual text #{some_ruby_stuff} in my heredoc, WITHOUT it being interpolated. Is there a way to escape the #{.

I've tried "\", but no luck. Although it escapes the #{}, it also includes the "\":

>> <<-END
 #{RAILS_ENV} \#{RAILS_ENV} 
END
=> " development \#{RAILS_ENV}\n"
Was it helpful?

Solution

I think the backslash-hash is just Ruby being helpful in some irb-only way.

>> a,b = 1,2        #=> [1, 2]
>> s = "#{a} \#{b}" #=> "1 \#{b}"
>> puts s           #=> 1 #{b}
>> s.size           #=> 6

So I think you already have the correct answer.

OTHER TIPS

For heredoc without having to hand-escape all your potential interpolations, you can use single-quote-style-heredoc. It works like this:

item = <<-'END'
  #{code} stuff
  whatever i want to say #{here}
END

You can use ' quotes instead. Anything enclosed in them is not being interpolated.

Your solution with escaping # also works for me. Indeed Ruby interpreter shows

=> "\#{anything}"

but

> puts "\#{anything}"
#{anything}
=> nil

Your string includes exactly what you wanted, only p method shows it with escape characters. Actually, p method shows you, how string should be written to get exactly object represented by its parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top