-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwords_analyser.rb
53 lines (44 loc) · 1.17 KB
/
words_analyser.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
require 'json'
class WordsAnalyser
def initialize(text, filter)
@words = text.split
@filter = filter.split
end
def highest_occurring_words(number_words)
Hash[words_occurrences.sort_by { |k,v| -v }[0..(number_words-1)]]
end
def words_occurrences
word_occurrences ||= filtered_words.inject(Hash.new(0)) do |result, word|
result[word] += 1
result
end
end
def highest_occurring_words_list(number_words)
list = highest_occurring_words(number_words).sort_by {|word, occs| occs}.reverse.map do |word, occs|
" #{word}: #{occs}"
end.join("\n")
"\n" + list + "\n"
end
def text_list
list = words_occurrences.sort_by {|word, occs| occs}.reverse.map do |word, occs|
" #{word}: #{occs}"
end.join("\n")
"\n" + list + "\n"
end
def html_list
list = words_occurrences.sort_by {|word, occs| occs}.reverse.map do |word, occs|
" <li>#{word}: #{occs}</li>"
end.join("\n")
"<ul>\n" + list + "\n</ul>"
end
def json_list
JSON.parse(filtered_words.to_json)
end
end
private
def filtered_words
filtered_words ||= @words.reject do |word|
word.downcase!
@filter.include?(word)
end
end