Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace characters in a string using two arrays

Tags:

text

replace

ruby

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?

like image 902
nevan king Avatar asked Dec 05 '25 19:12

nevan king


2 Answers

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.

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

rubyFiddle.

like image 54
alex Avatar answered Dec 08 '25 10:12

alex


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

like image 26
Ribtoks Avatar answered Dec 08 '25 09:12

Ribtoks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!