从ruby代码中使用ruby one liners

vin*_*ini 4 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
Run Code Online (Sandbox Code Playgroud)

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

dex*_*ter 14

根据ruby CLI参考,

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

因此,只需将代码段复制到gets()循环中的ruby文件即可

foob​​ar.rb

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

并使用执行文件

ruby foobar.rb < file.txt
Run Code Online (Sandbox Code Playgroud)

您还可以通过以编程方式读取文件来替换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
Run Code Online (Sandbox Code Playgroud)