user2527785
user2527785

Reputation: 117

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.

def(my_words,my_sentence)
  #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].up.case
      end
    end
  end

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

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

Upvotes: 0

Views: 1929

Answers (3)

Dan Grahn
Dan Grahn

Reputation: 9424

This will work better. It loops through the brands, searches for each, and replaces with the uppercase version.

brands = %w(sony toshiba)
sentence = "This is a sony. This is a toshiba."

brands.each do |brand|
  sentence.gsub!(/#{brand}/i, brand.upcase)
end

Results in the string.

"This is a SONY. This is a TOSHIBA."

For those who like Ruby foo!

sentence.gsub!(/#{brands.join('|')}/i) { |b| b.upcase }

And in a function

def capitalize_brands(brands, sentence)
  sentence.gsub(/#{brands.join('|')}/i) { |b| b.upcase }
end

Upvotes: 3

yozzz
yozzz

Reputation: 1287

You get this error because i doesn't start from 0 as you expected, in each method i is an element of array, and has string type, it's a first word from your sentence:

my_sentence_words = ["word"]
my_sentence_words.each do |i|
  puts i.length #=> 4
  puts i.type   #=> String
  puts i        #=> word
end

So you try to call my_sentence_words[word] instead of my_sentence_words[0]. You can try method each_index that passes index of element instead of element itself`:

def check(str, *arr)
  upstr = str.split(' ')
  upstr.eachindex do |i|       #=> i is index
    arr.each_index do  |j|  
      upstr[i].upcase! if upstr[i] == arr[j]        
    end
  end
  upstr
end

check("This is my sentence", "day", "is", "goal", "may", "my")
#=>["This", "IS", "MY", "sentence"]

Upvotes: 0

bjhaid
bjhaid

Reputation: 9782

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

Upvotes: 3

Related Questions