Forum: Ruby Creating InsensitiveHash in C

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0f1f17ba297242e9d3c86d4cc0a6ea85?d=identicon&s=25 Iñaki Baz Castillo (Guest)
on 2009-02-19 21:58
(Received via mailing list)
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:
  http://www.ruby-doc.org/core/classes/Hash.html
but I can't find it in Ruby libs directory.
8f6f95c4bd64d5f10dfddfdcd03c19d6?d=identicon&s=25 Rick Denatale (rdenatale)
on 2009-02-19 22:23
(Received via mailing list)
On Thu, Feb 19, 2009 at 3:57 PM, Iñaki Baz Castillo <ibc@aliax.net>
wrote:

>  => 0.5
>
> PD: Where is the C file defining Hash class? I read "hash.c" in Hash
> documentation:
>  http://www.ruby-doc.org/core/classes/Hash.html
> 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
0f1f17ba297242e9d3c86d4cc0a6ea85?d=identicon&s=25 Iñaki Baz Castillo (Guest)
on 2009-02-19 22:33
(Received via mailing list)
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.
This topic is locked and can not be replied to.