1

逆インデックスで部分一致を検索する必要があります。次のコードは完全一致では機能しますが、部分一致では機能しません。これをhttp://rosettacode.org/wiki/Inverted_Indexの例から作り直しました(Ruby1.9.3 では動作しなくなりました)。

それを最も効率的な方法で行う方法を教えてください。軽量でシンプルで純粋なRubyソリューションを知っていて、自分でやりたい場合を除き、Lucene、Sphinxなどの使用についてアドバイスしないでください。

@data = {"contents"=>["1.txt", "2.txt"], "of"=>["1.txt", "2.txt"], "file"=>["1.txt", "2.txt"], "one"=>["1.txt"], "two"=>["2.txt"]}

def search words
  result = []
  words.each do |word|
    result << @data[word] if @data[word] #should do a partial match
  end
  result
end

p search ['of'] #=> [["1.txt", "2.txt"]]
p search ['one'] #=> [["1.txt"]]
p search ['on']  #=> []                    <<should become [["1.txt"]]
4

1 に答える 1

3

次のように定義searchします。

def search words
  words.map do |word|
    matches = @data.keys.select {|key| key.include?(word)}
    matches.map {|match| @data[match] }
  end      
end

p search ['of'] #=> [[["1.txt", "2.txt"]]]
p search ['one'] #=> [[["1.txt"]]]
p search ['on']  #=> [[["1.txt", "2.txt"], ["1.txt"]]] - note that "contents" contains "on" 
于 2012-06-08T16:00:03.450 に答える