ordered hashes in ruby 1.8 19. Jun 2008

Ruby 1.8 doesn’t offer builtin ordered hashes, but there are several libraries out there which extend or replace Ruby’s Hash class. Among them are Ruby/RBTree, Ara T. Howard’s orderedhash and Ruby Facets. All three of these offer a hashlike syntax, letting you do things like

ordered_hash = Library['a', 1, 'b' ,2]

resulting in

{'a'=>1, 'b'=>2}

Sadly all three of these libraries have poor documentation. The one with most bearable in my eyes is Ruby Facet’s Dictionary, which also has a RubyGem available, so let’s have a look at it.

$ sudo gem install facets
Successfully installed facets-2.4.1
1 gem installed
Installing ri documentation for facets-2.4.1...
Installing RDoc documentation for facets-2.4.1...

Ruby Facets is a rather large library, so you’ll want to require just the Dictionary class.

>> require 'rubygems'
>> require 'facets/dictionary'

Let’s make an ordered hash with five elements and print it out.

>> dictionary = Dictionary[*(1..10)]
>> dictionary.each {|k,v| puts "#{k}=>#{v}"}
1=>2
3=>4
5=>6
7=>8
9=>10

Works fine. Now for the bonus round. Dictionary can also be used as a sorted hash by calling the order_by or more conveniently the order_by_key method. Once called this method ensures that all previously and subsequently inserted keys will be in sorting order.

>> array = Array.new(10){rand(100)}
>> dictionary = Dictionary[*array]
=> {1=>49, 48=>97, 17=>66, 6=>70, 52=>77}
>> dictionary.order_by_key
>> dictionary.each {|k,v| puts "#{k}=>#{v}"}
1=>49
6=>70
17=>66
48=>97
52=>77
 

Kommentare (2)

  1. Cool beans. Now I wonder if they could just rewrite Dictionary[] method to ‘look’ like a real hash [same syntax] by similar means as the rewrite gem uses. That would be fascinating!

  2. Stefan 47 days later

    Actually the documentation page of the Dictionary library lists an example which would probabably look like how you wanted, but neither does it work nor would it preserve insertation order if it actually worked.

    hsh = Dictionary['z'=>1, 'a'=>2, 'c'=>3]
    p hsh.keys #=> ['a','c','z']
    

    But despite this minor aesthetical glitch the library indeed rocks :)

Kommentar schreiben

Markdown Syntax