[英]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. 如果用户输入
Oz
,我想输出文件中包含单词Oz
所有电影。
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. 没有必要对所有的
each
东西。 Also the then
on an if
is almost never put in there, it's just useless decoration. 而且,
if
几乎没有, then
就放在if
上,那只是无用的装饰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.