Ruby will find the line in the file and the print result

It has been a long time since I used ruby โ€‹โ€‹for such things, but I forgot how to open the file, look for a line 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 that the "document root" (routes) is in config / routes.rb

If I print a line, it prints the file.

It seems to me that I do not remember what it is, but I need to know.

Hope I can do this:

 # Route is: blah blah blah blah 
+7
source share
3 answers
 File.open 'file.txt' do |file| file.find { |line| line =~ /regexp/ } end 

This will return the first line that matches the regular expression. If you need all the matching strings, change find to find_all .

It is also more efficient. It iterates through the lines one at a time, without loading the entire file into memory.

Alternatively, you can use the grep method:

 File.foreach('file.txt').grep /regexp/ 
+8
source

The easiest way to get root:

 rake routes | grep root 

If you want to do this 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 
+2
source

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

 f.each_line { |line| if line =~ /string/ then puts line end } 
+1
source

All Articles