首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Ruby中使用STDIN的最佳实践?

在Ruby中使用STDIN的最佳实践?
EN

Stack Overflow用户
提问于 2008-11-07 19:14:52
回答 9查看 202.6K关注 0票数 318

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

代码语言:javascript
复制
> cat input.txt | myprog.rb
> myprog.rb < input.txt
> myprog.rb arg1 arg2 arg3 ...

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

代码语言:javascript
复制
#!/usr/bin/env ruby

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

ARGV.each do |b|
    puts b
end
EN

回答 9

Stack Overflow用户

发布于 2011-03-03 11:13:08

Ruby提供了另一种处理STDIN的方法:-n标志。它将您的整个程序视为在STDIN上的循环中(包括作为命令行参数传递的文件)。例如,请参阅以下单行脚本:

代码语言:javascript
复制
#!/usr/bin/env ruby -n

#example.rb

puts "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
票数 44
EN

Stack Overflow用户

发布于 2008-11-07 19:51:40

我不太确定您需要什么,但我会使用以下内容:

代码语言:javascript
复制
#!/usr/bin/env ruby

until ARGV.empty? do
  puts "From arguments: #{ARGV.shift}"
end

while a = gets
  puts "From stdin: #{a}"
end

请注意,因为ARGV数组在第一个gets之前是空的,所以Ruby不会尝试将参数解释为可从中读取的文本文件(行为继承自Perl)。

如果stdin为空或没有参数,则不打印任何内容。

几个测试用例:

代码语言:javascript
复制
$ cat input.txt | ./myprog.rb
From stdin: line 1
From stdin: line 2

$ ./myprog.rb arg1 arg2 arg3
From arguments: arg1
From arguments: arg2
From arguments: arg3
hi!
From stdin: hi!
票数 33
EN

Stack Overflow用户

发布于 2008-11-07 20:53:14

也许是这样的东西?

代码语言:javascript
复制
#/usr/bin/env ruby

if $stdin.tty?
  ARGV.each do |file|
    puts "do something with this file: #{file}"
  end
else
  $stdin.each_line do |line|
    puts "do something with this line: #{line}"
  end
end

示例:

代码语言:javascript
复制
> cat input.txt | ./myprog.rb
do something with this line: this
do something with this line: is
do something with this line: a
do something with this line: test
> ./myprog.rb < input.txt 
do something with this line: this
do something with this line: is
do something with this line: a
do something with this line: test
> ./myprog.rb arg1 arg2 arg3
do something with this file: arg1
do something with this file: arg2
do something with this file: arg3
票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/273262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档