Creating InsensitiveHash in C

Hi, I’d like a faster Ruby class same as Hash but in which key and value
are
insensitive, so:


params = InsensitiveHash.new
params[“q”] = 0.5
params[“transport”] = “TCP”

params[“Q”]
=> 0.5

params[“Transport”] == “tcp”
=> true

It will be used extensively so I need it being very fast. I’m thinking
in
implementing it as a new Ruby class in C, modifying Hash class.

Do you think it’s feasible? Any suggestion?
Thanks a lot.

PD: Where is the C file defining Hash class? I read “hash.c” in Hash
documentation:
class Hash - RDoc Documentation
but I can’t find it in Ruby libs directory.

On Thu, Feb 19, 2009 at 3:57 PM, Iñaki Baz C. [email protected]
wrote:

=> 0.5

PD: Where is the C file defining Hash class? I read “hash.c” in Hash
documentation:
class Hash - RDoc Documentation
but I can’t find it in Ruby libs directory.

You won’t find it in a runtime installation of Ruby. The file hash.h is
in
the top level directory of the Ruby source code.

That said, If all you want to do is to make the keys case insensitive, a
naive Ruby implementation is likely to be almost as fast as anything you
could do in C, since the time intensitve implementation parts of Hash
are
already in C.

So something like

class InsensitiveHash
def initialize
@hash = {}
end

def [](key}
@hash[key.downcase]
end

def []=(key, value)
@hash[key.downcase] = value
end
end

And yes, I’d recommend having the InsensitiveHash have an instance of
Hash
rather than being a subclass of Hash.


Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

El Jueves, 19 de Febrero de 2009, Rick DeNatale escribió:

   @hash[key.downcase] = value
  end
end

And yes, I’d recommend having the InsensitiveHash have an instance of Hash
rather than being a subclass of Hash.

The fact is I already have something as above, but I wonder if using a
new
Ruby C native class would be really faster.

Thanks a lot.