Forum: Ruby Ruby equivalent for PHP's strtr?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
55fb785d1720b98e5ea97350f9d2c2d6?d=identicon&s=25 Jeroen Heijmans (Guest)
on 2006-03-12 11:35
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?


Jeroen Heijmans
0b561a629b87f0bbf71b45ee5a48febb?d=identicon&s=25 Dave Burt (Guest)
on 2006-03-12 13:49
(Received via mailing list)
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
of strtr(), which is the same as Ruby's tr.

The two argument version, with the arrays, isn't in standard Ruby, but
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 = {|a, b| a }
    values = {|a, b| b }
      /(#{{|a| Regexp.quote(a) }.join( ')|(' )})/
      ) { |match| values[keys.index(match)] }

# 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"

04a0f1074e1b621746954ccc73eec7d7?d=identicon&s=25 Matthew Harris (kuja)
on 2006-03-13 14:37
ri String#tr

- Matt
55fb785d1720b98e5ea97350f9d2c2d6?d=identicon&s=25 Jeroen Heijmans (Guest)
on 2006-03-13 20:21
Dave Burt 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.
This topic is locked and can not be replied to.