如何替换字符串中的字符 [英] How to replace the characters in a string

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

问题描述

我有一种方法可以用来替换字符串中的字符:

I have a method that I want to use to replace characters in a string:

def complexity_level_two
  replacements = {
      'i' => 'eye', 'e' => 'eei',
      'a' => 'aya', 'o' => 'oha'}
  word = "Cocoa!55"
  word_arr = word.split('')
  results = []
  word_arr.each { |char|
    if replacements[char] != nil
      results.push(char.to_s.gsub!(replacements[char]))
    else
      results.push(char)
    end
  }
end

我希望的字符串输出为:Cohacohaa!55

My desired output for the string should be: Cohacohaa!55

但是,当我运行此方法时,它不会替换字符,而只会输出字符串:

However when I run this method it will not replace the characters and only outputs the string:

C
o
c
o
a
!
5
5

该方法无法替换字符串内的正确字符以匹配hash中的字符时,我该怎么办?我如何解决此问题以获得所需的输出?

What am I doing wrong to where this method will not replace the correct characters inside of the string to match that in the hash and how can I fix this to get the desired output?

推荐答案

replacements = {
  'i' => 'eye', 'e' => 'eei',
  'a' => 'aya', 'o' => 'oha'}
word = "Cocoa!55"
word.gsub(Regexp.union(replacements.keys), replacements)
#⇒ "Cohacohaaya!55"

Regexp::union

Regexp::union, String#gsub with hash.

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

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