From: Joel VanderWerf Date: 2006-10-21T08:31:16+09:00 Subject: Re: multi dim array? Gavin Kistner wrote: > From: Robert Klemme [mailto:shortcutter@googlemail.com] >> irb(main):002:0> r={"a"=>"B","e"=>"X"} >> => {"a"=>"B", "e"=>"X"} >> irb(main):003:0> "message".gsub(/./){|k| r[k]||k } >> => "mXssBgX" > > Ooh, that's elegant, using gsub's block like that. > I think I'm going to steal it. > > (I don't have any need for it, but...you know...I gotta HAVE it.) > It might run faster if you do this: reg = Regexp.new(r.keys.map {|k| Regexp.quote(k)}.join("|")) p "message".gsub(reg){|k| r[k] } (The #quote is needed in case of r["|"] = "x", for example.) Saves you a hash lookup for each char. I guess it's faster, but I might be wrong. Benchmarking left as an exercise for the reader, i.e. I'm lazy :). -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407