Question

In Perl there is a __DATA__ token that allows input to be loaded from the program/script file itself. What is the Ruby equivalent?

Was it helpful?

Solution

Place the data after the __END__ token, read it in with DATA.read (which returns a String object), split the string on newline (\n), and iterate over the resultant Array with each or the like.

#!/usr/bin/env ruby

DATA.read.split(/\n/).each_with_index do |l,i|
        puts "line #{i+1}: #{l}"
end

__END__
red
orange
yellow
green
blue
indigo
violet

Example run:

-bash> ruby -W /tmp/x.rb 
line 1: red
line 2: orange
line 3: yellow
line 4: green
line 5: blue
line 6: indigo
line 7: violet
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top