Skip to main content
  1. Posts/

Ruby's DATA Stream

·285 words·2 mins·
Programming Languages

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.

# hello_world.rb
puts DATA.gets
__END__
hello world!

Let’s run the script:

$ 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:

Reply by Email

Related

Numbered Parameters in Ruby 2.7
·654 words·4 mins
Programming Languages

A new feature called “numbered parameters” will see the light of day in the Ruby 2.7 release at the end of the year. What caught my attention was not the feature itself but the mixed reception it got from the community.