簡體   English   中英

如何從文本文件中獲取匹配項並將其輸出到數組中?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM