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

时间:2013-12-10 18:14:33

标签: ruby arrays string loops

我正在尝试在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

3 个答案:

答案 0 :(得分:3)

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

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 }

在一个功能中

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

答案 1 :(得分:3)

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"

答案 2 :(得分:0)

您收到此错误是因为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]。您可以尝试通过each_index元素而不是元素本身`的方法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"]