user2527785 user2527785 - 11 months ago 52
Ruby Question

How to replace text in a ruby string

I am trying to write a very simple method in Ruby which takes a string and an array of words and checks if the string contains any of the words and if it does it replaces them with their uppercase.

I made an attempt but its not great due to my level of Ruby skills.

#split the sentence up into an array of words
my_sentence_words = my_sentence.split(/\W+/)
#nested loop that checks the words array for each brand
my_sentence_words.each do |i|
my_words.each do |i|
#if it finds a brand in the words and sets them to be uppercase
if my_words[i] == my_sentence_words[i]
my_sentence_words[i] == my_sentence_words[i]

#put the words array into one string
words.each do |i|
new_sentence = ("" + my_sentence_words[i]) + " "

I am getting:
can't convert string into integer error

Answer Source
def convert(mywords,sentence)
 regex = /#{mywords.join("|")}/i
 sentence.gsub(regex) { |m| m.upcase }
convert(%W{ john james jane }, "I like jane but prefer john")
#=> "I like JANE but prefer JOHN"