Skip to content

Instantly share code, notes, and snippets.

@mfifth
Created September 14, 2016 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfifth/b67ffe6b1324700bf30bdb15e3ead6b4 to your computer and use it in GitHub Desktop.
Save mfifth/b67ffe6b1324700bf30bdb15e3ead6b4 to your computer and use it in GitHub Desktop.
# SortCollectionRelevancy
#
# Sort any collection (array), with specific methods based on the word frequency
class SortCollectionRelevancy
def initialize(query, collection, methods = [])
@query = query
@collection = collection
@methods = Array(methods)
end
def sort
sort_collection(@query, @collection, @methods)
end
protected
def sort_collection(query, collection, methods)
query_words = normalize_words(query).uniq
collection.sort_by.with_index do |record, i|
word_count = methods.flat_map do |method|
normalize_words(record.send(method))
end.inject(Hash.new(0)) { |h, v| h.tap { h[v] += 1 }}
-word_count.values_at(*query_words).sum
end
end
def normalize_words(value)
value.split(/\W+/).map(&:downcase)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment