Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Ruby
Ruby equivalent for PHP's strtr?
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Dave Burt, post: 4508562"] Jeroen Heijmans asked: 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 [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Ruby
Ruby equivalent for PHP's strtr?
Top