[英]What's the most efficient way to search words in this kind of file by Ruby
我有一個類似的文件:
Fruit.Store={
#blabla
"customer-id:12345,item:store/apple" = 10; #blabla
"customer-id:23456,item:store/banana" = 10; #blabla
"customer-id:23456,item:store/watermelon" = 10;
#blabla
"customer-id:67890,item:store/watermelon" = 10;
}
除注釋外,每一行都具有相同的格式:customer-id和item:store /是固定的,customer-id是5位數字。 文件中大約有1000條唯一的行。 輸入“ 12345”和“ apple”時,應返回第一行。 Ruby解決此問題的最有效方法是什么? 謝謝!
def lookup(input, id, fruit)
IO.foreach(input).detect do |line|
line =~ %r|^\p{Space}*customer-id:#{id},item:store/#{fruit}|
end
end
lookup("/path/to/file", 12345, 'apple')
#⇒ " \"customer-id:12345,item:store/apple\" = 10; #blabla\n"
Ruby解決此問題的最有效方法是什么?
( 假設您可以一次將整個數據集加載到內存中並保存在那里。 )
加載時,將文件轉換為此形狀的哈希。
data = {
[12345, 'apple'] => 10,
[23456, 'banana'] => 10,
...
}
然后,您只需執行以下操作:
data[[12345, 'apple']] # => 10 or nil (if not found)
這使您可以進行O(1)查找。 您再沒有比這更有效率的了。
如果要直接處理文件,則可以逐行讀取文件並嘗試檢測匹配的行,如@mudasobwa的答案所示。 在這種情況下,查找效率要低得多,但是另一方面,它不需要預處理。 因此,如果您只想進行一次查找,則總體上可能會更有效率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.