From: Pit Capitain Date: 2001-08-24T18:57:48+09:00 Subject: [ruby-talk:20266] Re: ordered hash On 24 Aug 2001, at 9:31, Joseph McDonald 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. > > thanks, > -joe > Hi Joe, I once implemented an OrderedHash, but it was ordered according to the keys. Not quite what you need, sorry. But if you use an Array in your OrderedHash holding the keys in the order you want it should not be too much work. I would start with the methods you know you'll need and not worry about all the other Hash methods, something like class OrderedHash < Hash def []=( key, value ) ( @ordered_keys ||= [] ) << key unless has_key?( key ) super end def each @ordered_keys.each do | key | yield key, fetch( key ) end if @ordered_keys end end Test: h = OrderedHash.new h[ 3 ] = 1 h[ 4 ] = 1 h[ 5 ] = 9 h[ 2 ] = 6 h[ 5 ] = 3 h.each { | k, v | puts "#{k} => #{v}" } gives 3 => 1 4 => 1 5 => 3 2 => 6 This simple implementation lacks a lot of Hash's features, but if Hash.new, Hash#[], Hash#[]=, Hash#each are all you need it should be enough. Pit