Skip to content

Instantly share code, notes, and snippets.

@aokolish
Created July 25, 2017 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aokolish/50d13d031c3dfdd1598d69dd369f8037 to your computer and use it in GitHub Desktop.
Save aokolish/50d13d031c3dfdd1598d69dd369f8037 to your computer and use it in GitHub Desktop.
def replace_words(dict, sentence)
regex = /\A(#{dict.join('|')})/
sentence.split.inject([]) do |new_words, word|
if match_data = word.match(regex)
new_words << match_data.captures[0]
else
new_words << word
end
end.join(' ')
end
puts replace_words(['cat', 'bat', 'rat'], "the cattle was rattled by the battery")
# -------------------------------------
# James solution
dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
def replace_words2(dict, sentence)
tokens = sentence.split(' ').map do |word|
prefix(dict, word)
end
puts tokens.join " "
end
def prefix(dict, word)
dict.each do |prefix|
return prefix if word.match(/^#{prefix}/)
end
word
end
x = replace_words2(dict, sentence)
puts "RESULT: #{x}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment