__END__ Before I learned about __END__ (a directive that causes Ruby to cease processing a source code file), whenever I was testing little snippets or scripts which relied on reading data from somewhere, I would keep a test.csv or something similar open while I was writing my code. I would switch between the Ruby file and the CSV (or alternative). Especially for small snippets, it sometimes felt like a cumbersome way to develop. However, __END__ can often solve this problem. If you put an __END__ in a Ruby file, everything after the __END__ will be accessible as a file in the DATA variable. Let's say we have a file example.rb : puts "DATA is a #{DATA.class}"
puts DATA.read
__END__
here is some
data, that, i,
have
and we run it: $ ruby example.rb
DATA is a File
here is some
data, that, i,
have
We've confirmed both the class of DATA and that we can easily access it. I would not necessarily recommend storing any information past the __END__ in production applications or environments, but I do find it useful for iterating on snippets of code which rely on some data. It's helpful to be able to edit sample data inline while having access to the code that's ingesting the data. |