如何替换ruby字符串中的文本

我试图在Ruby中编写一个非常简单的方法,它接受一个字符串和一个单词数组,并检查字符串是否包含任何单词,如果是,它将用大写字母替换它们。

我做了一个尝试,但由于我的Ruby技能水平,它并不是很好。

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 

我得到: can't convert string into integer error

 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" 

这会更好。 它遍历品牌,搜索每个品牌,并替换为大写版本。

 brands = %w(sony toshiba) sentence = "This is a sony. This is a toshiba." brands.each do |brand| sentence.gsub!(/#{brand}/i, brand.upcase) end 

结果在字符串中。

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

对于那些喜欢Ruby foo的人!

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

并在一个function

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

你得到这个错误,因为i没有像你期望的那样从0开始,在each方法中i是数组元素,并且有字符串类型,它是你句子中的第一个单词:

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

因此,您尝试调用my_sentence_words[word]而不是my_sentence_words[0] 。 你可以尝试传递元素index而不是元素本身的方法each_index:

 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"]