Take the 2-minute tour ×

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

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
share|improve this question
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
add comment

3 Answers

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}"
share|improve this answer
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. –  CodeGnome May 31 '12 at 11:47
+1 for rake routes. –  Matheus Moreira May 31 '12 at 12:03
add comment

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
share|improve this answer
add comment
File.open 'file.txt' do |file|
  file.find { |line| line =~ /regexp/ }

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/
share|improve this answer
add comment

Your Answer

