![](/img/trans.png)
[英]How do I get a text output from a string created from an array to remain unshortened?
[英]How do I get matches from a text file and output them in an array?
我正在使用带有电影行的文本文件。 如果用户输入Oz
,我想输出文件中包含单词Oz
所有电影。
到目前为止,这就是我所拥有的。
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
假设您已将文件整理成这样:
Wizard of Oz
Battlefield Earth
Twilight
Ozymandias
然后,您可以通过以下方式阅读它:
lines = File.readlines('movies.txt').map(&:chomp)
然后找到匹配的行:
matches = lines.grep(phrase)
没有必要对所有的each
东西。 而且, if
几乎没有, then
就放在if
上,那只是无用的装饰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.