Ruby's DATA Stream

Ghent,

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:


tagged: Ruby

Related posts

The contents for this page are licensed CC-BY-SA.