juretta.com

Ruby SequencedHash

December 29, 2006
Tags: Gems Ruby
Is there a pure-ruby ordered hash? I'm looking for something that will preserve the order in which key/value pairs were entered.

Although one might argue that a Hash that preserves insertion order is not what a Hash is meant to be - sometimes that is exactly what you need.

The new Ruby gem collections contains some classes (right now only two, but more classes are to be expected) that make life a tad easier when working with collections.

The following code excerpt shows an easy usage example for a SequencedHash.

macbook:~ stefan$ sudo gem install collections
Successfully installed collections-0.1.1
Installing ri documentation for collections-0.1.1...
Installing RDoc documentation for collections-0.1.1...
require 'rubygems'
#  require 'collections'
#  # or
require 'collections/sequenced_hash'
hash = SequencedHash.new
hash[:v1] = "v1"
hash[:v2] = "v2"
hash[:v3] = "v3"
puts hash.inspect # => {:v1=>"v1", :v2=>"v2", :v3=>"v3"}
puts hash.at(0) # => "v1"
puts hash.at(1) # => "v2"        

About

This is the defunct blog of Stefan Saasen.