3 ms·
For non-rubyists, what does this example do? Are those labels?
by Udo 14y ago
For non-rubyists, what does this example do? Are those labels?
- venus 14y agoThat's ruby's heredoc syntax: http://en.wikipedia.org/wiki/Here_document http://en.wikipedia.org/wiki/Here_document I had no idea it could be nested like that and I've been using ruby for 8 years. Crazy!
- mitchty 14y agoHoly cow, 10 years for me and I've never even thought of nesting heredocs. Some days I wish Matz would formalize the grammar so it is sane.
- ahlatimer 14y agoIt's a way of writing strings without having to escape things or having line breaks mess things up (a heredoc, if you're familiar with that terminology). For instance, <<-END this is some text END will give you a string containing " this is some text\n". END can be anything. It's particularly useful in metaprogramming, since you can maintain formatting, and you don't have to escape " or ' if they happen to show up in your code. What's interesting in the OP's example is that you end up passing three strings " text of one\n", " text of two\n", " text of three\n". I had no idea that would happen, though I have seen things like define_method <<-RUBY, __FILE__, __LINE__ + 1 some_code RUBY so it makes sense. Ruby treats anything on the same line after the comma as separate arguments, so even though __FILE__ comes after <<-RUBY and before RUBY, it really appears after the final RUBY to the interpreter.
- dllthomas 14y agoAs another non-rubyist with too much perl and bash under my belt, I'm guessing it's heredoc - the <<-FOO syntax means "grab the lines following until you see FOO alone on a line, shove it all in a string, and pass it as this argument (in bash it passes a filename that represents half of a pipe which has been sent the content).