Best practices with STDIN in Ruby? [closed] Best practices with STDIN in Ruby? [closed] ruby ruby

Best practices with STDIN in Ruby? [closed]


Following are some things I found in my collection of obscure Ruby.

So, in Ruby, a simple no-bells implementation of the Unix command cat would be:

#!/usr/bin/env rubyputs ARGF.read

ARGF is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.

ARGF.each_with_index do |line, idx|    print ARGF.filename, ":", idx, ";", lineend# print all the lines in every file passed via command line that contains loginARGF.each do |line|    puts line if line =~ /login/end

Thank goodness we didn’t get the diamond operator in Ruby, but we did get ARGF as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, -i) to every file mentioned on the command-line:

#!/usr/bin/env ruby -iHeader = DATA.readARGF.each_line do |e|  puts Header if ARGF.pos - e.length == 0  puts eend__END__#--# Copyright (C) 2007 Fancypants, Inc.#++

Credit to:


Ruby provides another way to handle STDIN: The -n flag. It treats your entire program as being inside a loop over STDIN, (including files passed as command line args). See e.g. the following 1-line script:

#!/usr/bin/env ruby -n#example.rbputs "hello: #{$_}" #prepend 'hello:' to each line from STDIN#these will all work:# ./example.rb < input.txt# cat input.txt | ./example.rb# ./example.rb input.txt


I am not quite sure what you need, but I would use something like this:

#!/usr/bin/env rubyuntil ARGV.empty? do  puts "From arguments: #{ARGV.shift}"endwhile a = gets  puts "From stdin: #{a}"end

Note that because ARGV array is empty before first gets, Ruby won't try to interpret argument as text file from which to read (behaviour inherited from Perl).

If stdin is empty or there is no arguments, nothing is printed.

Few test cases:

$ cat input.txt | ./myprog.rbFrom stdin: line 1From stdin: line 2$ ./myprog.rb arg1 arg2 arg3From arguments: arg1From arguments: arg2From arguments: arg3hi!From stdin: hi!