我想在Ruby中处理命令行输入:

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

最好的方法是什么?我特别想处理空白的STDIN,我希望有一个优雅的解决方案。

#!/usr/bin/env ruby

STDIN.read.split("\n").each do |a|
   puts a
end

ARGV.each do |b|
    puts b
end

当前回答

你也可以使用STDIN。each_line和STDIN.each_line。To_a将其作为数组获取。

e.g.

STDIN.each_line do |line|
  puts line
end

其他回答

简单快捷:

STDIN.gets.chomp == 'YES'

我是这样做的:

all_lines = ""
ARGV.each do |line|
  all_lines << line + "\n"
end
puts all_lines

你也可以使用STDIN。each_line和STDIN.each_line。To_a将其作为数组获取。

e.g.

STDIN.each_line do |line|
  puts line
end

以下是我在收藏的一些不知名的Ruby代码中发现的一些东西。

因此,在Ruby中,Unix命令的简单无铃实现 猫会是: # !/usr/bin/env红宝石 把ARGF.read ——https://web.archive.org/web/20080725055721/http: / / www.oreillynet.com/ruby/blog/2007/04/trivial_scripting_with_ruby.html评论- 565558

ARGF在输入方面是你的朋友;它是一个虚拟文件,从命名文件或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. #++ — http://blog.nicksieger.com/articles/2007/10/06/obscure-and-ugly-perlisms-in-ruby

信贷:

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

while STDIN.gets
  puts $_
end

while ARGF.gets
  puts $_
end

这是受到Perl的启发:

while(<STDIN>){
  print "$_\n"
}