Ruby's big DATA
constant does more than you might expect!
Everything after the __END__
keyword (at the beginning of the line) is not interpreted as Ruby, but can be retrieved with the big¹ DATA
constant.² This is an example big-data.rb
script:
p DATA.read
__END__
big data
Big DATA
is a File object, which you can read
. The example will output "big data"
. An example of real-world usage is inline templating within the sinatra web framework.³
¹ Do not confuse with the small Data
class, which is a CRuby implementation detail
² Big DATA
is not defined, if you have no __END__
. Furthermore, it is not available if you did not execute the script directly, but loaded or required it.
³ Actually, not really
Is the Data Section Enough?
Wait a minute! Big DATA
is a File object? What file exactly?
p DATA.path
p DATA.lineno
__END__
big data
The output will be "big-data.rb"
and 3
. The big DATA
object points to the source file itself at a specific position! And look, we can alter this:
DATA.rewind
puts DATA.gets("\n__END__")[0..-9]
__END__
big data
It will now read the source code of itself:
DATA.rewind
puts DATA.gets("\n__END__")[0..-9]
Also See
More Idiosyncratic Ruby
- Please Comment on GitHub
- Next Article: Escape Back Referencing
- Previous Article: Magic Instructions