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
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.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 you don't need to report the locations of the matches and the file is not overly large, you could just do this:
Let's try it:
File.read(F_NAME)
returns the entire text file in a single string.scan /\b#{input}\b/i
is sent to that string.