Skip to content

re: Under the Hood: “Slurping” and Streaming Files in Ruby VIEW POST


Thanks to Ruby's Perl inspired past, it's also easy to process files line by line from the command line (the current line is in the $_ magic variable) which can replace quite a few awkward shell pipelines:

ruby -n -e 'puts $_.swapcase' foo.txt

Another neat trick is using Enumerator::Lazy to only read as much of the file as you need, i.e. { |line| line.match(/Ruby/) }.first(5)

to output the first 5 lines that contains the word 'Ruby'.

code of conduct - report abuse