Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices with STDIN in Ruby? [closed]

Tags:

ruby

stdin

I want to deal with the command line input in Ruby:

> cat input.txt | myprog.rb > myprog.rb < input.txt > myprog.rb arg1 arg2 arg3 ... 

What is the best way to do it? In particular I want to deal with blank STDIN, and I hope for an elegant solution.

#!/usr/bin/env ruby  STDIN.read.split("\n").each do |a|    puts a end  ARGV.each do |b|     puts b end 
like image 387
griflet Avatar asked Nov 07 '08 19:11

griflet


People also ask

How do you stop a stdin input?

press CTRL-D to end your input. This is the right answer. Ctrl-D is the canonical way to terminate keyboard stdin in any shell command.

What is $Stdin in Ruby?

The $stdin is a global variable that holds a stream for the standard input. It can be used to read input from the console. reading.rb. #!/usr/bin/ruby inp = $stdin.read puts inp. In the above code, we use the read method to read input from the console.

What is ARGF in Ruby?

ARGF is a stream designed for use in scripts that process files given as command-line arguments or passed in via STDIN. The arguments passed to your script are stored in the ARGV Array , one argument per element. ARGF assumes that any arguments that aren't filenames have been removed from ARGV .


1 Answers

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 ruby puts 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, ";", line end  # print all the lines in every file passed via command line that contains login ARGF.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 -i  Header = DATA.read  ARGF.each_line do |e|   puts Header if ARGF.pos - e.length == 0   puts e end  __END__ #-- # Copyright (C) 2007 Fancypants, Inc. #++ 

Credit to:

  • https://web.archive.org/web/20080725055721/http://www.oreillynet.com/ruby/blog/2007/04/trivial_scripting_with_ruby.html#comment-565558
  • http://blog.nicksieger.com/articles/2007/10/06/obscure-and-ugly-perlisms-in-ruby
like image 61
Jonke Avatar answered Oct 13 '22 09:10

Jonke