Available for hire
Ordered Hashes in Ruby 1.8

So I came across a situation where I needed an ordered hash. After doing some research and talking to the #rubyonrails guys I’ve found I’m far from the only one who needs this, and in Ruby 1.9 there is a OrderedHash class. But until then I had to create my own, and with the help of the guys in #rubyonrails I finally got something working

# lib/ordered_hash.rb
class OrderedHash < Hash
  def initialize
    @keys = []
    super
  end

  def []=(key, value) 
    @keys << key unless member?(key)
    super
  end

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

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

Usage is as follows!

# Usage:
h = OrderedHash.new
h[2] = 3
h["x"] = "y"
h.delete(3)
h.each {|key| p key}

Yea its pretty simple, but I’m still pretty new at all of this, so I chalk this as another milestone!

Comments