ruby - 使用 ruby​​ 代码中的 ruby​​ one liners

标签 ruby

我读到了 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/

相关文章:

ruby-on-rails - 数组参数上的 rspec 匹配器类似于 hash_including

ruby-on-rails - 急切加载多态关联的第一条记录

ruby-on-rails - 从数组创建哈希的最简洁方法

ruby-on-rails - Rails 应用程序中对/etc/localtime 的过多 stat 调用

更新证书后,Ruby Net::HTTP 响应 OpenSSL::SSL::SSLError "certificate verify failed"

ruby-on-rails - 像这样 a = b = c = d = 5 分配多个变量是否正确?

ruby - Sass::Util:Module 的未定义方法 `has?' (NoMethodError) - Debian 上使用 Ruby、Sass、Compass 时出错

ruby - RSpec 的 before、after 和 around 钩子(Hook)以什么顺序运行?

ruby - 如何处理 Rails 中的加密 URL?

ruby - 如何将 erubi 模板呈现为 html?