How to replace text in a ruby string

前端 未结 3 1145
醉梦人生
醉梦人生 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: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
    

提交回复
热议问题