From: "Jesús Gabriel y Galán" Date: 2008-09-01T21:25:48+09:00 Subject: Re: gsub html sanitizer On Mon, Sep 1, 2008 at 2:09 PM, Chealsea S. wrote: > 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 :) If you don't mind a loop, you could gsub each pattern one at a time. irb(main):002:0> patterns = {"apple" => "fruit", "cat" => "animal", "flower" => "plant"} => {"cat"=>"animal", "apple"=>"fruit", "flower"=>"plant"} irb(main):003:0> s = "apple cat flower" => "apple cat flower" irb(main):004:0> patterns.each {|p,r| s.gsub!(p, r)} => {"cat"=>"animal", "apple"=>"fruit", "flower"=>"plant"} irb(main):005:0> s => "fruit animal plant" You could also build a big regexp and let gsub do the loop: irb(main):008:0> s = "apple cat flower" => "apple cat flower" irb(main):009:0> re = Regexp.new("(#{patterns.keys.join("|")})") => /(cat|apple|flower)/ irb(main):010:0> s.gsub(re) {patterns[$1]} => "fruit animal plant" Hope this helps, Jesus.