0

This seems to work correctly and display the results I want

Dir["/Users/ondrovic/RubyTest/**/*.txt"].each do |i|
    puts i.green if File.readlines(i).grep(/test/).any?
end

Why when I try like this does it not populate info

print "Enter search dir"
src = gets
print "Enter search term"
trm = gets

puts "Looking in #{src} for #{trm}"

Dir["#{src}/**/*.txt"].each do |i|
    puts i.green if File.readlines(i).grep(/"#{trm}"/).any?
end

I have also tried it this way

Dir[src + "/**/*.txt"].each do |i|
   puts i.green if File.readlines(i).grep(/ + trm + /).any?
end

Working code

require 'colorize'
print "Enter search dir\n".green
src = gets.chomp
print "Enter search term\n".blue
trm = gets.chomp

puts "Looking in #{src} for #{trm}"

Dir["#{src}/**/*.txt"].each do |i|
    puts i.green if File.readlines(i).grep(/#{trm}/).any?
end
1
  • 1
    replace /"#{trm}"/ with /#{trm}/ Commented Oct 12, 2014 at 1:32

1 Answer 1

2

The return value of the gets includes trailing newline:

>> gets
asdf
=> "asdf\n"  # <----
>>

Remove it using String#chomp:

print "Enter search dir"
src = gets.chomp
print "Enter search term"
trm = gets.chomp
...

In addition to that, the pattern /"#{trm}"/ includes ". Remove them:

/#{trm}/

Alternatively, you can use Regexp::new:

Regexp.new(trm)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.