![](/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.