How to replace text in a ruby string

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

提交回复
热议问题