Forum: Ruby Ruby equivalent for PHP's strtr?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jeroen Heijmans (Guest)
on 2006-03-12 12: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?


thanks,

Jeroen Heijmans
Dave B. (Guest)
on 2006-03-12 14: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
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
Matthew H. (Guest)
on 2006-03-13 15:37
ri String#tr

- Matt
Jeroen Heijmans (Guest)
on 2006-03-13 21:21
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.
This topic is locked and can not be replied to.