On Fri, Aug 3, 2012 at 6:59 PM, Wayne Brisette <wbrisett / att.net> 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!(/>/, "&lt;").gsub!(/</, "&gt;)
>
> but I found that work, so for now I'm using:
>
> my_string.gsub!(/>/, "&lt;")
> my_string.gsub!(/</, "&gt;)
>
> 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 = {
  '>' => '&lt;',
  '<' => '&gt;'
}

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("<a>").to_s
=> "&lt;a&gt;"

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/