|
|
|
SearchCategories
Books by the AuthorOther Ruby Projects |
Working With Multiline Strings
Posted 9 months ago
in Ruby Tutorials and Ruby Voodoo.
I imagine most Rubyists are aware that Ruby has "heredocs," but do you really know all they can do? Let's find out. A "here document" is a literal syntax for a multiline String. In the most basic form, they look like this:
The There are some important details in that description, namely that the String begins on the next line and that it's inserted where the heredoc was started. This means that the rest of the line where the heredoc is started can have normal Ruby code (though your editor may syntax highlight it badly):
The spacing in the above example was to make it easier for a human to understand, but I use Taking it one step further, the content of the rest of the line can include another heredoc. The second one will begin on the line after the first ends. This continues on down for however many you care to make:
Another interesting thing to know about heredocs is that they are double-quoted Strings by default. You can use any escapes allowed there as well as interpolation:
However, if you would prefer single-quoted behavior, you can just surround the heredoc name with single quotes:
There's one more trick with regard to heredoc syntax. If you begin with
That String of code will have a bunch of whitespace at the beginning of each line. The space before the end marker is not counted though. This doesn't affect the code of course, but you need to keep it in mind for other content. A final point of interest that may be of value to TextMate users: TextMate will properly syntax highlight the contents of Hopefully all of this gives you some new ideas for ways you might handle multiline Strings with Ruby. You don't need heredocs everywhere, but they can clean things up with the right usage. |
|
|
|
I thought I knew heredocs, but I never knew about the
<<END_SQL.gsub(/\s+/, " ").striptrick. Thanks for the solid post./g
I never knew about
<<'SINGLE_QUOTED'nor the difference between<<STRand<<-STR. Thanks!Just great - I really enjoy posts that look at one small feature and go in deep. Like the other commenters, there are some neat aspects to heredocs that I didn't know or forgotten about. Thanks!
This is good stuff. Thank you.