使用两个数组替换字符串中的字符

时间:2020-12-12 12:20:02

I'd like to use two arrays to change characters in a string. The first array would have the original characters, the second would have the replacement characters.

我想用两个数组来改变字符串中的字符。第一个数组将具有原始字符,第二个数组将具有替换字符。

original = ["a", "b", "c"]
replacements = ["x", "y", "z"]
text = "a xx b xx c"
# New string should be "x xx y xx z"

Is there an easy way to do this in Ruby?

在Ruby中有没有一种简单的方法?

3 个解决方案

#1


7  

You would use String#tr to do the replacements, and Array#join to turn your arrays into strings, which is what String#tr expects as arguments.

您将使用字符串#tr进行替换,使用数组#join将数组转换为字符串,这是字符串#tr期望的参数。

new_text = text.tr(original.join, replacements.join)

rubyFiddle.

rubyFiddle。

#2


6  

Take a look at the String#tr method http://ruby-doc.org/core-1.9.3/String.html#method-i-tr

看看字符串#tr方法http://ruby-doc.org/core-1.9.3/String.html#method-i-tr

#3


0  

original = ["/", ".", ",", "|"]
replacements = ["_", "_", "_", "__"]

i = 0
original.each do |char|
  text.scan(char).size.times do
    text.sub!(char, replacements[i])
  end
  i = i+1
end

#1


7  

You would use String#tr to do the replacements, and Array#join to turn your arrays into strings, which is what String#tr expects as arguments.

您将使用字符串#tr进行替换,使用数组#join将数组转换为字符串,这是字符串#tr期望的参数。

new_text = text.tr(original.join, replacements.join)

rubyFiddle.

rubyFiddle。

#2


6  

Take a look at the String#tr method http://ruby-doc.org/core-1.9.3/String.html#method-i-tr

看看字符串#tr方法http://ruby-doc.org/core-1.9.3/String.html#method-i-tr

#3


0  

original = ["/", ".", ",", "|"]
replacements = ["_", "_", "_", "__"]

i = 0
original.each do |char|
  text.scan(char).size.times do
    text.sub!(char, replacements[i])
  end
  i = i+1
end