How to Access Data After the '__END__' Block?
In Ruby, the __END__
keyword is used to tell the parser to stop executing the source file. It is often used to store code snippets and notes about the script that weren’t really needed inline, and for appending documentation such as a license file to the end of a source code file.
Content of the file following the __END__
keyword is available via the global IO object named DATA
. It contains all the content after __END__
in that Ruby script file.
How can this be useful? Let’s try it out. In the example below I’ll use it for quick scripts where I need to process text data, rather than piping to STDIN
.
DATA.each_line.map(&:chomp).each do |url|
`open "#{url}"`
end
__END__
https://www.toptal.com/
www.toptal.com/ruby/tips-and-practices
Not that useful? Ok, let’s say you have a bunch of CSV data where you want only one column from, and you want to use that CSV data and DATA
to pull out the field you want:
require "csv"
CSV.parse(DATA, headers: true).each do |row|
puts "#{row['Name']} => #{row['URL']}"
end
__END__
Id,Name,URL
1,Eqbal,https://www.toptal.com/resume/eqbal-quran
2,Diego,http://https://www.toptal.com/resume/diego-ballona
This is pretty cool. Still don’t believe me? Consider the last example. Let’s say you just want to use DATA to contain ERB templates:
require 'erb'
number = rand(100)
erb = ERB.new(DATA.read)
puts erb.result()
__END__
Here is a randon number: <%= number %>.
Contributors
Eqbal Quran
Eqbal is a senior full-stack developer with more than a decade of experience working in web and mobile development. He is a masterful problem solver and boasts an extensive portfolio of finished professional products.
Show More