Add something new to Virb:

Virb

Are you sure you want to delete that?

or Cancel

 

Posted on Feb 10, 2009

Useless Ruby Tricks: DATA and __END__

So maybe not totally useless certainly fun. Normally, ruby scripts are finished when you reach the end of a file; however, this is not always the case. You can end your script sooner by using the __END__ keyword in your script. Once added, everything you type after that will not be parsed by ruby.


So what?


Well, you can use the global variable DATA to get the contents of what you wrote after the __END__ block. DATA is actually a File object to just that piece of text in your script.



How about a little sample to make things a little clearer?


#!/usr/bin/env ruby
%w(yaml pp).each { |dep| require dep }

obj = YAML::load(DATA)

pp obj

__END__
---
-
name: Adam
age: 28
admin: true
-
name: Maggie
age: 28
admin: false

So with this, I was able to embed a little bit of YAML directly into my script. I added the YAML after __END__. YAML::load will accept a File object, so I just passed it DATA and now I have a reconstituted array.


Maybe that's not the most practical use of this information; however, Sinatra provides a really awesome use of this.

Loading comments...

Likes

Details

Viewed 18 times

© 2009 Pope

virb.com/t/1080611
tweet!

Flag this text post!

Flag this text post as:

or Cancel

 

Advertisement

Flag this profile!

Flag this profile as:

or Cancel