Ruby Heredoc Substitute - happiness through readability

By: Johnathon Wright on: October 01, 2008

Sometimes you just have a paste a crazy-long string into your code. I find myself doing this often when it comes to testing. It might even have single and double quotes, so it's awkward to put quotes around the area and escape the quotes.

One solution is Ruby's implementation of the heredoc. Essentially, you're saying, "This is a string. Go ahead and process this as a string until I give you the magic word . In the following example, "DOCUMENT" is the magic word.

---ruby

secret = 'PASSWORD' => "PASSWORD"

my_text =<<-DOCUMENT Yoda says, 'confusing to escape this is: """ """" ;;;; ''''' .' My password is secretly #{secret} you could go on for a while here. DOCUMENT

=> " Yoda says, 'confusing to escape this is: \"\"\" \"\"\"\" ;;;; ''''' .'\n My password is secretly PASSWORD\n you could go on for a while here.\n"

So that's nice. Assuming you don't have #{} anywhere in your text, this works great. However, the word DOCUMENT doesn't exactly jump out as obvious.

"Andy Stone":http://blog.stonean.com/ showed a syntax he often uses. Though the syntax is perl-like in it cryptic-ness, if that is a word, and I think that it is not, still, it seems better. Closing token is a pipe ( ), which Andy says he doesn't often find in strings.

---ruby

my_text = %| Yoda says, 'confusing to escape this is: """ """" ;;;; ''''' .' My password is secretly #{secret} you could go on for a while here.|

=> "\n Yoda says, 'confusing to escape this is: \"\"\" \"\"\"\" ;;;; ''''' .'\n My password is secretly PASSWORD\n you could go on for a while here.\n"

It's not perfect, but certainly better. Certainly the pipe is a nicer closing token.





Comments:

Just checking that you are human. What would be the result of this code?

a = 3*(4/2); b = 1; a+b

Back