13

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"
Rosa
  • 642
  • 6
  • 20
Nick
  • 518
  • 1
  • 4
  • 16

3 Answers3

21

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
austinfromboston
  • 3,791
  • 25
  • 25
19

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.

Mike Woodhouse
  • 51,832
  • 12
  • 88
  • 127
4

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.

Mike Woodhouse
  • 51,832
  • 12
  • 88
  • 127
samuil
  • 5,001
  • 1
  • 37
  • 44
  • Perhaps I wasn't clear enough - this is within a heredoc. I've updated the example to reflect that better. – Nick Aug 21 '09 at 08:34
  • 1
    the same still holds. `"\#{anything}" == '#{anything}'` No interpolation, and the generated string doesn't actually contain a backslash. `irb` just displays one since it's using `String#inspect`. Try `puts < – rampion Aug 21 '09 at 09:24