views:

229

answers:

3

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"

Thx Nick

+2  A: 

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.

samuil
Perhaps I wasn't clear enough - this is within a heredoc. I've updated the example to reflect that better.
Nick
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 <<END` to see the (uninspected) string.
rampion
+6  A: 

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
You're right. irb was being "helpful".Thx
Nick
+2  A: 

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