9

Idiosyncratic Ruby: Big Data Without End

 3 years ago
source link: https://idiosyncratic-ruby.com/59-big-data-without-end.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Big Data Without End

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


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK