14 comments

[ 3.1 ms ] story [ 43.8 ms ] thread
This is copied from Perl. See http://stackoverflow.com/questions/161872/hidden-features-of...

  my @lines = <DATA>;
  for (@lines) {
      print if /bad/;
  }
  
  __DATA__
  some good data
  some bad data
  more good data 
  more good data
As quite a good few things in ruby are. Having never really learned perl, I keep discovering them anew in ruby first :-)
And widely used in the perl world. It's a good idea for a lot of simple programs.
Agreed, this is not a "hidden feature."
Which had copied this (including the "DATA" name) from good old BASIC:

     10 DATA 1,2,3,4,5,6,7,8,9
     20 FOR I=1 TO 9
     30 READ A(I)
     40 NEXT I
I learnt about this a while back when sinatra was released, you could have your html template in the same file. great idea for a micro framework.
I'd forgotten sinatra let you do this, I remember it being really nice for a small simple app with a couple of templates.
Minor correction (mostly because, I think the code is kinda interesting), Sinatra does something close to this. It actually uses the __END__ tag for its inline templates, but then internally it splits the file itself in two and then parses the latter portion:

https://github.com/sinatra/sinatra/blob/master/lib/sinatra/b...

I suspect the reason it does so is for the point the author of the article makes briefly: "And it only exists for the first ruby file to be invoked by the interpreter."

I wrote a static-site generator, and I wanted to be able to allow users to deploy new instances easily.

To do that I wrote some code that parses a __DATA__ block for lines like:

mkdir foo create_file foo/bar.txt <<EOF .. This is the file content .. EOF mkdir bar ..

The process was very simple and allowed me to bundle up the "master template" files in one simple to understand resource.

[1] - https://github.com/skx/templer [2] - https://raw.github.com/skx/templer/master/lib/Templer/Site/N...

I had thought that the ability to do a simple quine by rewinding DATA was some weird implementation bug, so nice to see the rationale here !