Hacker News new | past | comments | ask | show | jobs | submit login
Ruby DATA (caiustheory.com)
45 points by EzGraphs on Jan 9, 2013 | hide | past | favorite | 14 comments



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


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


As quite a good few things in ruby are. Having never really learned perl, I keep discovering them anew in ruby first :-)


And in Perl there are also: __FILE__ , __LINE__ , __PACKAGE__ , __SUB__ & __END__

These are called Special Literals - http://perldoc.perl.org/perldata.html#Special-Literals


Ruby also has __FILE__ and __LINE__.


Yep. And in Perl6 these were changed to:

    __LINE__            $?LINE
    __FILE__            $?FILE
    __PACKAGE__         $?PACKAGE
    __END__             =begin END
    __DATA__            =begin DATA
ref: http://feather.perl6.nl/syn/S02.html#Double-underscore_forms


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.


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'd forgotten sinatra let you do this, I remember it being really nice for a small simple app with a couple of templates.


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...


Nice!


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 !




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: