Created
July 25, 2017 00:51
-
-
Save aokolish/50d13d031c3dfdd1598d69dd369f8037 to your computer and use it in GitHub Desktop.
This file contains 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 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