Question

I'm trying to take input from the user, search through a text file (case insensitively), and then display the match from the file if it matches (with the case of the word in the file). I don't know how to get the word from the file, here's my code:

found = 0
words = [] 

puts "Please enter a word to add to text file"
input = gets.chomp

#Open text file in read mode 
File.open("filename", "r+") do |f|

  f.each do |line|
    if line.match(/\b#{input}\b/i)
      puts "#{input} was found in the file."   # <--- I want to show the matched word here
      #Set to 1 indicating word was found
      found = 1
    end
  end
end 
Était-ce utile?

La solution

So, what you want to do is to store the result of the match method, you can then get the actual matched word out of that, ie.

if m = line.match( /\b#{input}\b/i )
  puts "#{m[0]} was found in the file."
  # ... etc.
end

Update

Btw, you didn't ask - but I would use scan in this case, so that I got an array of the matched words on each line (for when there's more than one match on the same line), something like this:

if m = line.scan( /\b#{input}\b/i )
  puts "Matches found on line #{f.lineno}: #{m.join(', ')}"
  # ... etc.
end

Autres conseils

If you don't need to report the locations of the matches and the file is not overly large, you could just do this:

File.read("testfile").scan /\b#{input}\b/i

Let's try it:

text = <<THE_END
Now is the time for all good people
to come to the aid of their local
grocers, because grocers are important
to our well-being.  One more thing.
Grocers sell ice cream, and boy do I
love ice cream.
THE_END

input = "grocers"
F_NAME = "text"
File.write(F_NAME, text)

File.read(F_NAME).scan /\b#{input}\b/i
  # => ["grocers", "grocers", "Grocers"]

File.read(F_NAME) returns the entire text file in a single string. scan /\b#{input}\b/i is sent to that string.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top