How to replace text in a ruby string

前端 未结 3 1106
醉梦人生
醉梦人生 2021-01-27 06:24

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 w

相关标签:
3条回答
  • 2021-01-27 06:51
    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"
    
    0 讨论(0)
  • 2021-01-27 06:53

    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
    
    0 讨论(0)
  • 2021-01-27 07:13

    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"]
    
    0 讨论(0)
提交回复
热议问题