简体   繁体   中英

How do I get matches from a text file and output them in an array?

I'm using a text file with lines of movies. If a user inputs Oz , I want to output all the movies in the file that have the word Oz in it.

This is what I have so far.

puts "Enter the keyword you want to search for: "
keyword = gets
movies_file = File.new("movies.txt", "r")
movies = movies_file.read
movies_list = movies.split(" ")
match_list = []
movies_list.each do |w|
  matchObj = w.match(keyword)
  if matchObj then
    matchlist.push(matchObj.captures[0])
  end
end
match_list.each do |title|
  puts title
end

Presuming you've got the file organized like this:

Wizard of Oz
Battlefield Earth
Twilight
Ozymandias

Then you can read it in this way:

lines = File.readlines('movies.txt').map(&:chomp)

Then to find matching lines:

matches = lines.grep(phrase)

There's no need for all the each stuff. Also the then on an if is almost never put in there, it's just useless decoration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM