Ruby在文件和打印结果中查找字符串

8 ruby ruby-on-rails

自从我将ruby用于这样的事情已经很长时间了,但是,我忘记了如何打开文件,查找字符串以及打印ruby发现的内容.这是我有的:

#!/usr/bin/env ruby
f = File.new("file.txt")
text = f.read
if text =~ /string/ then
puts test
end
Run Code Online (Sandbox Code Playgroud)

我想确定config/routes.rb中的"文档根"(路由)是什么

如果我打印字符串,它会打印文件.

我感到愚蠢,我不记得这是什么,但我需要知道.

希望我可以打印出来:

# Route is:
blah blah blah blah
Run Code Online (Sandbox Code Playgroud)

Mat*_*ira 12

File.open 'file.txt' do |file|
  file.find { |line| line =~ /regexp/ }
end
Run Code Online (Sandbox Code Playgroud)

这将返回与正则表达式匹配的第一行.如果您想要所有匹配的行,请更改findfind_all.

它也更有效率.它一次迭代一行,而不将整个文件加载到内存中.

此外,该grep方法可以使用:

File.foreach('file.txt').grep /regexp/
Run Code Online (Sandbox Code Playgroud)


gma*_*iar 2

在里面text你有整个文件作为一个字符串,你可以使用正则表达式来匹配它.match,或者像 Dave Newton 建议的那样,你可以迭代每一行并检查。例如:

f.each_line do |line|
  puts line if line =~ /string/
end
Run Code Online (Sandbox Code Playgroud)