♦️ BEGIN, END, and the END of the World
BEGIN and END blocks are the unsung heroes of Ruby one-liners. They give you setup and teardown for free, turning a simple-ne loop into a proper little program. Plus, Ruby lets you embed data right inside your script with __END__. Because sometimes your config file and your script should just be the same file.
Part 1: BEGIN and END Blocks
Like Perl'sBEGIN and END blocks, these run before and after your main code.
# Perl: BEGIN { $count = 0 } # main code runs here END { print "Total: $count\n" }
# Ruby: BEGIN { $count = 0 } # main code runs here END { puts "Total: #{$count}" }
Part 2: One-Liner Power
This is where BEGIN/END really shine. Adding setup and teardown to one-liners:# Count error lines ruby -ne 'BEGIN{$n=0}; $n+=1 if /error/i; END{puts $n}' logfile.txt # Perl: perl -ne 'BEGIN{$n=0} $n++ if /error/i; END{print "$n\n"}' logfile.txt # Track unique IPs and report count ruby -ne 'BEGIN{$ips={}}; $ips[$1]=1 if /(\d+\.\d+\.\d+\.\d+)/; END{puts $ips.keys.length}' access.log # Sum a column ruby -ane 'BEGIN{$sum=0}; $sum += $F[2].to_f; END{puts $sum}' data.txt
BEGIN runs before ANY code, even require statements that appear before it in the file. END runs after all code completes, even if an exception was raised. They're bulletproof bookends.
Part 3: DATA and END
Ruby has a mechanism for embedding data inside your script, just like Perl's__DATA__ section.
# Perl: while (<DATA>) { chomp; print "Got: $_\n"; } __DATA__ line one line two line three
# Ruby: DATA.each_line do |line| line.chomp! puts "Got: #{line}" end __END__ line one line two line three
Part 4: Practical Embedded Config
One file. Script and config together. No external dependencies. Perfect for quick utilities where you don't want to manage a separate config file.#!/usr/bin/env ruby # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Parse embedded config # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ config = {} DATA.each_line do |line| line.chomp! next if line.empty? || line =~ %r~^#~ key, value = line.split(%r~\s*=\s*~, 2) config[key] = value end puts config.inspect __END__ # Server configuration host = localhost port = 5432 user = admin database = production
Part 5: Key Differences from Perl
| Perl | Ruby | Notes |
|---|---|---|
__DATA__ |
__END__ |
Different keyword |
<DATA> |
DATA.each_line |
Ruby uses IO object methods |
| Works in any file | Only works in main script | Not available in required files |
DATA is an IO object positioned right after the __END__ line. You can only read it once unless you seek back to the beginning with DATA.rewind.
Created By: Wildcard Wizard. Copyright 2026