Skip to content
loading...

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

FULL DISCUSSION
 

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.

 file.each_line.lazy.select { |line| line.match(/Ruby/) }.first(5)

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

code of conduct - report abuse