On Fri, Aug 3, 2012 at 6:59 PM, Wayne Brisette <[email protected]> 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("<a>").to_s
=> "<a>"
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en