From: Robert Klemme Date: 2012-08-04T19:56:00+09:00 Subject: Re: Stacking gsub! commands? On Fri, Aug 3, 2012 at 6:59 PM, Wayne Brisette wrote: > I have a script that I wrote that uses nokogiri to parse some HTML, the results > I get back, I need to change several of the HTML entities (><&), I thought I > could stack the gsub! commands so they would be something like this: > > my_string.gsub!(/>/, "<").gsub!(/ > but I found that work, so for now I'm using: > > my_string.gsub!(/>/, "<") > my_string.gsub!(/ > which works, but I'm sure is horribly inefficient. What makes you so sure? > Is there a better way to do > multiple global substitutions on a string? REPLACEMENTS = { '>' => '<', '<' => '>' } RX = Regexp.union(REPLACEMENTS.keys) my_string.gsub! RX do |m| replacements.fetch m do raise "Not found: #{m}" end end Use an XML tool: irb(main):001:0> require 'rexml/text' => true irb(main):002:0> s = REXML::Text.new("").to_s => "<a>" Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/