我读到了 Dave Thomas Ruby one liners
它说
# 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 代码而不是命令行吗?
最佳答案
根据 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
关于ruby - 使用 ruby 代码中的 ruby one liners,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309234/