Ruby’s DATA Stream

The STDIN and ARGF streams are commonly used in Ruby, however there’s also the less popular DATA one. This is how it works and some examples in the wild.

HOW TO READ FROM DATA?

Like with any other stream you can use gets and readlines. This behaviour is defined by the IO class. However there’s a caveat, your script needs to have a data section. To define it use the __END__ to separate code from data.

$ cat hello_world.rb
puts DATA.gets
__END__
hello world!

$ ruby hello_world.rb
hello world!

Look at that, another way to code hello world in Ruby. Without the __END__keyword, you’ll get the following error:

NameError: uninitialized constant DATA

WHEN TO USE IT?

You could use the data section of the script if you wanted to keep the data and code really close, or if you wanted to do some sort of pre processing to your sources. But to be honest, the only real benefit I can think of is performance. Instead of starting a second IO operation, to read a file containing the data, it’d get loaded at the same time than the script.

EXAMPLES

One thing I’ve learned while working with Go, is to check Go’s source files for good examples. Even though you cannot do this with Ruby at the same degree because the sources are in C, you can still check the parts of the sources that are in Ruby and the gems and tools maintained within the Ruby sources. Here are some examples:

Leave a Reply

Your email address will not be published. Required fields are marked *