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
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.
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.
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 .
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With