Re: multi dim array?

From: Robert K. [mailto:[email protected]]

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.)

Gavin K. wrote:

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
:).