Last active
April 19, 2017 04:04
-
-
Save tmikeschu/406872b8d0bf2c624b51a70056e28897 to your computer and use it in GitHub Desktop.
Most frequently used word codewars challenge https://www.codewars.com/kata/most-frequently-used-words-in-a-text/ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def top_3_words(text) | |
sterilized_words(text).reduce({}, &count_words) | |
.sort_by(&by_count).map(&first).reverse.take(3) | |
end | |
def count_words | |
lambda do |result, word| | |
result[word] = (result[word] || 0) + 1 ; | |
result | |
end | |
end | |
def by_count | |
-> _word, count { count } | |
end | |
def first | |
-> pair { pair[0] } | |
end | |
def sterilized_words(text) | |
text.gsub("\n", " ").split(" ").reject(&:empty?).reject(&no_letters).map(&sterilized) | |
end | |
def no_letters | |
-> word { word.chars.none?(&is_letter?) } | |
end | |
def is_letter? | |
-> char { char.match(/[a-z]/i) } | |
end | |
def sterilized | |
-> word { word.scan(/[a-z']/i).join.downcase } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment