From: Robert Klemme Date: 2008-09-01T21:25:06+09:00 Subject: Re: gsub html sanitizer 2008/9/1 Chealsea S. : > I'm new to Ruby and a bit confused about how gsub works. I've read the > documentation, searched ruby-forum, and tried numerous google searches, > but can't seem to figure out how to do something that should be simple. > > This is just an example, but say I have a string "apple cat flower". I'd > like to replace all instances of the pattern "apple" with the string > "fruit," "cat" with the string "animal," and "flower" with the string > "plant." Meaning I have more than 1 pattern to replace, each with a > specific string to replace. > > So I want "apple cat flower" to be converted into "fruit animal plant". > > I hope this isn't too confusing. Help is appreciated :) As long as the number of strings is not too large you can use Regexp.union: irb(main):004:0> replacements = {"apple"=>"fruit","cat"=>"animal","flower"=>"plant"} => {"cat"=>"animal", "apple"=>"fruit", "flower"=>"plant"} irb(main):005:0> Regexp.union replacements.keys => /cat|apple|flower/ irb(main):006:0> "apple cat flower".gsub(Regexp.union(replacements.keys)) {|m| replacements[m]} => "fruit animal plant" If the number increases you probably rather want something like this irb(main):007:0> "apple cat flower".gsub(/\w+/) {|m| replacements[m] || m} => "fruit animal plant" Kind regards robert -- use.inject do |as, often| as.you_can - without end