Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby Solution To Phrase Synonym Count Winner
# 1) Write a function which takes a phrase.
# 2) Phrase is "May the force be with you"
# 3) Which of these words has the most synonyms
require 'json'
require 'net/http'
API_KEY = 'SECRET'
BASE_URL = "http://thesaurus.altervista.org/service.php?language=en_US&output=json&key=#{API_KEY}&word=";
def synonym_data(word)
uri = URI.parse "#{BASE_URL}#{word}"
JSON.parse Net::HTTP.get(uri)
end
def synonyms_from_data(data)
return [] if data['error']
lists = data['response']
lists.map { |list|
synonyms = list['list']['synonyms'].split('|')
synonyms.reject! { |s| s =~ /\(antonym\)/ } # Antonyms are not Synonyms.
synonyms.map { |s| s.sub /\s\(.*\)/, '' } # Remove things like " (related term)"
}.flatten.uniq
end
def synonym_count(word)
data = synonym_data(word)
synonyms_from_data(data).length
end
def phrase_to_words_and_synonym_count_hash(phrase)
words = phrase.split ' '
counts = words.map { |w| Thread.new(w) { |word| synonym_count(word) } }.collect(&:value)
Hash[words.zip(counts)]
end
def word_with_most_synonyms_from_phrase(phrase)
data = phrase_to_words_and_synonym_count_hash(phrase)
most = data.values.max
word = data.detect { |w,c| c == most }
{word: word[0], count: word[1]}
end
word_with_most_synonyms_from_phrase "May the force be with you" # => {word: "force", count: 62}
@jpfuentes2

This comment has been minimized.

Show comment
Hide comment
@jpfuentes2

jpfuentes2 Feb 25, 2015

Thread#(current|join) can be simplified to Thread#value:

def phrase_to_words_and_synonym_count_hash(phrase)
  words = phrase.split ' '
  counts = words.map do |w|
    Thread.new(w) { |word| synonym_count(word) }
  end.collect(&:value)
  Hash[words.zip(counts)]
end

Thread#(current|join) can be simplified to Thread#value:

def phrase_to_words_and_synonym_count_hash(phrase)
  words = phrase.split ' '
  counts = words.map do |w|
    Thread.new(w) { |word| synonym_count(word) }
  end.collect(&:value)
  Hash[words.zip(counts)]
end
@metaskills

This comment has been minimized.

Show comment
Hide comment
@metaskills

metaskills Feb 25, 2015

I love it! 😊

Owner

metaskills commented Feb 25, 2015

I love it! 😊

@metaskills

This comment has been minimized.

Show comment
Hide comment
@metaskills

metaskills Feb 26, 2015

Made a few updates. The word_with_most_synonyms_from_phrase returns a Hash now.

Owner

metaskills commented Feb 26, 2015

Made a few updates. The word_with_most_synonyms_from_phrase returns a Hash now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment