How to replace text in a ruby string

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

提交回复
热议问题