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?
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.
Take a look at the String#tr method http://ruby-doc.org/core-1.9.3/String.html#method-i-tr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With