Ruby equivalent for PHP's strtr?

Hi, I’m looking for a function that can do the same thing as the strtr
function in PHP (and possibly other languages, I don’t know). That is, I
would like to replace multiple parts of a strings simultaneously, so
that you can (among others) swap strings:

strtr(“AA BB”, array(“AA” => “BB”, “BB” => “AA”)); // “BB AA”

I’ve been trying to find a Ruby equivalent, but haven’t so far. The tr
functions in String only deal with single characters, and replace or
gsub only deal with one replacement at a time.

Any functions that I missed, or perhaps a library with this
functionality available?

thanks,

Jeroen Heijmans

Jeroen Heijmans asked:

Any functions that I missed, or perhaps a library with this
functionality available?

tr comes from Perl, where it has the meaning of PHP’s three-argument
version
of strtr(), which is the same as Ruby’s tr.

The two argument version, with the arrays, isn’t in standard Ruby, but
to
get equivalent functionality, you’d have to do something like this:

class String

PHP’s two argument version of strtr

def strtr(replace_pairs)
keys = replace_pairs.map {|a, b| a }
values = replace_pairs.map {|a, b| b }
self.gsub(
/(#{keys.map{|a| Regexp.quote(a) }.join( ‘)|(’ )})/
) { |match| values[keys.index(match)] }
end
end

Call using a hash for the replacement pairs:

“AA BB”.strtr(“AA” => “BB”, “BB” => “AA”) #=> “BB AA”

Or use an array of pairs if order matters

“AA BB”.strtr([[“AA”, “BB”], [“BB”, “AA”]]) #=> “BB AA”

Cheers,
Dave

ri String#tr

  • Matt

Dave B. wrote:

you’d have to do something like this:

Thanks, exactly what I was looking for.

ri String#tr

Yes, I have read this (as I mentioned in my post), but String#tr only
handles single characters, not strings.