Ruby find string in file and print result
ruby, ruby-on-rails
Solution
File.open 'file.txt' do |file|
file.find { |line| line =~ /regexp/ }
end
That will return the first line that matches the regular expression. If you want all matching lines, change `find` to `find_all`.
It's also more efficient. It iterates over the lines one at a time, without loading the entire file into memory.
Also, the `grep` method can be used:
File.foreach('file.txt').grep /regexp/
Problem
It's been a very long time since I've used ruby for things like this but, I forget how to open a file, look for a string, and print what ruby finds. Here is what I have: ``` #!/usr/bin/env ruby f = File.new("file.txt") text = f.read if text =~ /string/ then puts test end ``` I want to determine what the "document root" (routes) is in config/routes.rb If I print the string, it prints the file. I feel dumb that I don't remember what this is, but I need to know. Hopefully, I can make it print this: ``` # Route is: blah blah blah blah ```