Home > Blockchain >  Iterate through an array against another, and if true, do something
Iterate through an array against another, and if true, do something

Time:03-21

So, if you have a sentence as a string:

sentence = "Good morning, i'm doing well today."

Then turn it into an array of sub-strings:

words = sentence.split(" ")
> ["Good", "morning,", "i'm", "doing", "well", "today."]

And you have a WordBank model that has the following record:

word_to_find: "i'm"
replace_with: "I'm"

I want to be able to iterate through the words, and check against the WordBank. If returns true, replace that sub-string with the corrected replacement.

words.each do |word|
  if WordBank.all.map { \f| f.word_to_find == word } 
    print "True"
  end
end
> True

words.each |word|
  if WordBank.all.map { |f| f.word_to_find == word }
    word == .replace_with
  end
end

where .replace_with, I need to be able to call the same WordBank record that returned true, but can't figure out how.

So the end result should return an array

> ["Good", "morning", "I'm", "doing", "well", "today."]

which can then be put back to the sentence variable as:

sentence = words.join(" ")

If there's a more efficient way to do this, please feel free to let me know.

CodePudding user response:

sentence = "Good morning, i'm doing well today."
wordbank = [ { word_to_find: "i'm", replace_with: "I'm" } ]
wordbank.map { |f| sentence.gsub(f[:word_to_find], f[:replace_with]) }

CodePudding user response:

We can create a wordbank hash and loop over it to replace it without checking since it would only replace word if exists in the sentence.

gsub is used to replace word inside sentence since we want to replace inplace we included the ! version

wordbank = {
  "i'm": "I'm"
}
sentence = "Good morning, i'm doing well today."
wordbank.each do |k, v|
  sentence.gsub!(k, v)
end
  • Related