ruby - word-count
This commit is contained in:
parent
d16fe6a02a
commit
eb41f1b49f
@ -1,14 +1,20 @@
|
|||||||
|
# Phrase class
|
||||||
class Phrase
|
class Phrase
|
||||||
def initialize(phrase)
|
def initialize(phrase)
|
||||||
@phrase = phrase
|
@words = phrase.downcase.scan(/\w+(?:'\w)*/)
|
||||||
end
|
end
|
||||||
|
|
||||||
def word_count
|
def word_count
|
||||||
counts = {}
|
Hash[word_counts]
|
||||||
@phrase.scan(/\w+(?:'\w)*/).each do |word|
|
|
||||||
word.downcase!
|
|
||||||
counts[word] = counts[word].to_i + 1
|
|
||||||
end
|
end
|
||||||
counts
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def word_groups
|
||||||
|
@words.group_by { |word| word }
|
||||||
|
end
|
||||||
|
|
||||||
|
def word_counts
|
||||||
|
word_groups.map { |word, list| [word, list.size] }
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
Loading…
x
Reference in New Issue
Block a user