Class: Search

Inherits:
Object
  • Object
show all
Defined in:
lib/search.rb,
lib/search/cli.rb,
lib/search/version.rb

Defined Under Namespace

Classes: CLI, Error

Constant Summary collapse

VERSION =
"0.1.1"

Instance Method Summary collapse

Constructor Details

#initialize(search, haystack:) ⇒ Search

Initializes a new search.

search - A String describing the term to search for. haystack - A String to search.



9
10
11
12
# File 'lib/search.rb', line 9

def initialize(search, haystack:)
  @search = search
  @haystack = haystack
end

Instance Method Details

#qualityObject

Get the match quality.

The quality is determined by how many of the search words the haystack contains.

Example

search = Search.new('one two'
  haystack: 'one two three four'
)
search.quality
# => 50

Returns an Integer describing the percentage of search words present in the haystack.



51
52
53
54
55
# File 'lib/search.rb', line 51

def quality
  (search_words_present_in_haystack.count.to_f / search_words.count.to_f * 100).round
rescue ZeroDivisionError
  0
end

#suggestionsObject

Get suggestions for narrowing the search.

Example

search = Search.new('what is the meaning of',
  haystack: 'What is the meaning of life? And what is the meaning of lol?'
)

search.suggestions
# => [
#   [' life', ' lol']
# ]

Returns an Array of Strings that would narrow the search.



28
29
30
31
32
33
34
35
36
# File 'lib/search.rb', line 28

def suggestions
  suggestions = []

  @haystack.scan /#{@search}(?<suggestion>\b[^.?!]+\b{1,5})/io do |match|
    suggestions << match.first
  end

  suggestions
end