从ruby代码中使用ruby one liners

时间:2011-11-29 10:28:15

标签: ruby

我读过Dave Thomas Ruby的一个衬垫

它说

  # print section of file between two regular expressions, /foo/ and /bar/
      $  ruby -ne '@found=true if $_ =~ /foo/; next unless @found; puts $_; exit if $_ =~ /bar/' < file.txt

我可以知道如何使用这是我的Ruby代码而不是命令行吗?

1 个答案:

答案 0 :(得分:14)

根据ruby CLI参考,

-n              assume 'while gets(); ... end' loop around your script
-e 'command'    one line of script. Several -e's allowed. Omit [programfile]

因此,只需将代码段复制到gets()循环

中的ruby文件即可

<强> foobar.rb

while gets()
   @found=true if $_ =~ /foo/
   next unless @found
   puts $_
   exit if $_ =~ /bar/
end

使用

执行文件
ruby foobar.rb < file.txt

您还可以通过以编程方式读取文件来替换IO重定向

file = File.new("file.txt", "r")
while (line = file.gets)
   @found=true if line =~ /foo/
   next unless @found
   puts line
   exit if line =~ /bar/
end