Quirky Ruby Feature - Mixing Code and Data
Ruby has some fun quirky features. One of them is that you can mix code and data in a single file using the special keywords __END__
and DATA
. This is a weird concept, but Ruby allows you to use the script itself as a source of data.
References:
- https://docs.ruby-lang.org/en/3.0/Object.html#DATA
- https://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-__END__
The documentation says about __END__
:
Denotes the end of the regular source code section of a program file. Lines below __END__ will not be executed. Those lines will be available via the special filehandle DATA. The following code will print out two stanzas of personal information. Note that __END__ has to be flush left, and has to be the only thing on its line.
The way I use this is for one-off scripts. For example, doing coding challenges or demos. I used this extensively when doing the Advent of Code last year. I had contained the dataset and the logic for each daily exercise in a single script.
DATA.each do | line |
p line.chomp
end
END
this a line
this another line
This will print out each line below __END__.
Pretty neat!
Basically, Ruby ignores everything after __END__
when executing the script, BUT all of the data becomes available in the special object DATA
, which is actually a File object.