Ruby 中 STDIN 的最佳实践? [英] Best practices with STDIN in Ruby?

查看:47
本文介绍了Ruby 中 STDIN 的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

以下是我在晦涩难懂的 Ruby 收藏中发现的一些内容.

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

因此,在 Ruby 中,Unix 命令 cat 的简单无铃实现将是:

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

#!/usr/bin/env ruby
puts ARGF.read

ARGF 是您输入的朋友;它是一个虚拟文件,从命名文件中获取所有输入或从 STDIN 中获取所有输入.

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

谢天谢地,我们没有在 Ruby 中获得菱形运算符,但我们确实获得了 ARGF 作为替代品.虽然晦涩难懂,但事实证明它很有用.考虑这个程序,它在命令行中提到的每个文件中就地添加版权标头(感谢另一个 Perlism,-i):

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.
#++

归功于:

这篇关于Ruby 中 STDIN 的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆