删除部分字符串(小写)并在 Ruby 中保留原始字符串(大写)

Remove part of string (downcase) and keep the original (upcase) in Ruby

我想从 ruby 字符串中删除一组单词,使用这些单词的小写和无重音版本,并保留具有当前大小写和当前重音的原始字符串。

例如:

string = "Château Dupont Vallée du Rhône" 
stopwords= "vallee du Rhone"

期望的输出:string = "Château Dupont"

到目前为止我能做的是使用小写无重音字符串删除单词:

string = "chateau dupont vallee du rhone" 
stopword = "vallee du rhone"

示例输出:string = "chateau dupont"

事实上,我想获取原始字符串,但使用单词的小写无重音版本删除了一个字符串。

我的代码:

def remove_appellations_in_string(string, region_id)
   down_trans_string = I18n.transliterate(string.dup)      
   # custom request to order by max length in name            
   stopwords.each do |stop|
      # downcase/unaccent stopword
      down_trans_stop = I18n.transliterate(stop.name.downcase)
      # remove
      down_trans_string.gsub!(down_trans_stop, ' ')
    end    
    return ' ' + string + ' ' 
  end

我想我需要使用正则表达式或找到一种方法来获取停用词的索引以将它们从原始字符串中删除。

这似乎有效:

string = "Château Dupont Vallée du Rhône"   
stopword = "vallee du rhone"  
index = I18n.transliterate(string).downcase.index(I18n.transliterate(stopword).downcase)
string[0..(index - 1)] + string[(index + stopword.length)..-1]

# => "Château Dupont "

stopword = "Dupont" 
index = I18n.transliterate(string).downcase.index(I18n.transliterate(stopword).downcase)
string[0..(index - 1)] + string[(index + stopword.length)..-1]

# => "Château  Vallée du Rhône"

它按照您的建议进行 - 获取停用词与剥离字符串匹配的位置的索引,以及 returns 其前后的文本。

这就是你想要的吗?如果您有任何问题,请告诉我您的进展情况。