14

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
  • 1
    Wouldn't you want to iterate over each line rather than the entire file? In any case, a simple web search will provide an abundance of examples for this. – Dave Newton May 31 '12 at 11:24

3 Answers3

17
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/
Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
3

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
iain
  • 16,204
  • 4
  • 37
  • 41
  • 1
    Thanks for pointing the OP to `rake routes`. My only suggestion would be that one should use fgrep or `grep --fixed-strings` if one isn't trying to match a regular expression. – Todd A. Jacobs May 31 '12 at 11:47
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 { |line|
  if line =~ /string/ then
    puts line
  end
}
undur_gongor
  • 15,657
  • 5
  • 63
  • 75
gmaliar
  • 5,294
  • 1
  • 28
  • 36