如何替换红宝石字符串中的文本 [英] How to replace text in a ruby string

查看:59
本文介绍了如何替换红宝石字符串中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Ruby写一个非常简单的方法,该方法接受一个字符串和一个单词数组,并检查该字符串是否包含任何单词,如果确实包含任何单词,则将其替换为大写字母.

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 with their uppercase.

我尝试过一次,但是由于我的Ruby技能水平不高.

I made an attempt but its not great due to my level of Ruby skills.

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"

这篇关于如何替换红宝石字符串中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆