Alex Rivera | Logout

Ruby find string in file and print result

Asked 2012-05-31T11:10:27.650
15

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
Edit
Report

2 Answers

4

The simplest way to get the root is to do:

rake routes | grep root

If you want to do it in Ruby, I would go with:

File.open("config/routes.rb") do |f|
  f.each_line do |line|
    if line =~ /root/
      puts "Found root: #{line}"
    end
  end
end
answered 2012-05-31T11:32:09.073
2

Inside text you have the whole file as a string, you can either match against it using a .match with regexp or as Dave Newton suggested you can just iterate over each line and check. Something such as:

f.each_line do |line|
  puts line if line =~ /string/
end
answered 2012-05-31T11:30:27.760

Your Answer