Menu:

Post History:

Animals Matter to Me

Optional behavior for Ruby heredocs

It’s right there in the documentation but since I haven’t seen all of these usages of Ruby heredocs much, I thought it was worth mentioning. The first example is standard, the other two are less common:

<<HEREDOC
This is like a double quoted string
Interpolation happens here. #{1+2}
Backslashes are interpreted as escapes. \a\t
HEREDOC

=> "This is like a double quoted string\nInterpolation happens here. 3\n
Backslashes are interpreted as escapes. \a\t\n"

<<'HEREDOC'
Interpolation doesn't happen here. #{1+2}
Backslashes are not interpreted as escapes. \a\t
HEREDOC

=> "Interpolation doesn't happen here. \#{1+2}\nBackslashes are not 
interpreted as escapes. \\a\\t\n"

<<`HEREDOC`
uname -a
uptime
HEREDOC

=> "Linux kelethin 2.6.27-11-generic #1 SMP Thu Jan 29 19:24:39 UTC 2009 
i686 GNU/Linux\n 21:50:27 up 2 days,  2:25,  5 users, load average: 0.20,
 0.11, 0.03\n"

0 comments


Adding new comments is currently disabled.