Michael Neumann wrote:

> TAKAHASHI Masayoshi wrote:
>> Hi,
>> 
>> Joseph McDonald <joe / vpop.net> wrote:
>> >   Has anyone implemented an OrderedHash in ruby?  That is:
>> >   Hash.each { } will return items in the order that they were
>> >   inserted.  Just want to avoid re-inventing the wheel.
> 
> 
> You can also use Array#assoc to implement an ordered hash.
> But I assume it's very slow compared to a real hash.
> 
> An example:
> 
>   h = []
> 
>   h << ["key", "value"]
>   h << ["a",   2]
> 
> Now to get a value out of the array:
> 
>   h.assoc("key")[1]   # =>  value
> 
> 
> Regards,
> 
>   Michael
> 
> 

I just stumbled upon this implementation as I looked through httpmail-ruby:

class OrderedHash < Hash
        alias_method :store, :[]=
        alias_method :each_pair, :each

        def initialize
                @keys = []
        end

        def []=(key, val)
                @keys << key
                super
        end

        def delete(key)
                @keys.delete(key)
                super
        end

        def each
                @keys.each { |k| yield k, self[k] }
        end

        def each_key
                @keys.each { |k| yield k }
        end

        def each_value
                @keys.each { |k| yield self[k] }
        end
end

-- 
Ryan Tarpine, rtarpine / hotmail.com
"Technology is a queer thing.  It brings you great gifts
in one hand, and it stabs you in the back with the other."
         -- C.P. Snow