Ruby equivalent for PHP's strtr?

J

Jeroen Heijmans

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
 
D

Dave Burt

Jeroen Heijmans asked:
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?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top