EPICBRONY EPICBRONY - 5 months ago 7
Ruby Question

How do I search for a piece of text in a text file, and then print out the whole line of text containing the piece I was searching for in ruby?

This would be used in a search engine esc. manor, so that you can serch a text file and print out everything that is on its line, I.E.

File:
Ruby Is an Awesome programming language!

Query: Ruby
What is returned: Ruby Is an Awesome programming language!


How I do it, is beyond me. So does anyone know how to do it?

Answer

This example assumes the text is entered in a string with carriage returns as line breaks.

def search(string, query)
    string = string.split("\n"); 
    string.each do |line|
        if line.include?(query)
            return line
        end 
    end 
end 

You would call the method as follows:

test_string = "Hello, I'm a test string. \n Did you know that Ruby is pretty cool? \n Of course I did!"
search(test_string, "Did you")

EDIT

In the case that the string is found more than once, this will return all instances:

def search(string, query)
    string.split("\n").select{ |line| line.include?(query)}
end 
Comments