Quirky Ruby Feature - Mixing Code and Data

/assets/images/uploads/2025/ac0161604f-6242519f.jpg

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:

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.