Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby maintain Hash insertion order

Tags:

hashtable

ruby

I am looking for a way to maintain the insert order for a Hash that I am using in Ruby. My data is coming from a database and is already grouped/ordered the way I want it, but Ruby doesn't guarantee maintained order in Hashs in my version 1.8.4.

Is there any workaround for this? If not is there a way I could create a custom comparator?

Here is the Hash:

{
"February"=>[0.5667, 14.6834, 79.7666, 261.8668, 342.1167, 723.517], 
"March"=>[0.0, 26.4667, 554.45, 681.3164, 2376.0668, 10353.0358], 
"May"=>[2.75, 34.6666, 342.1831, 1331.8999, 1589.617, 9282.9662], 
"July"=>[1.9, 2.3666, 59.45, 302.1501, 554.1652, 5195.0839], 
"June"=>[0.15, 24.2166, 244.1498, 335.6834, 536.067, 1498.949], 
"August"=>[0.0, 0.4, 9.3668, 30.7164, 67.7504, 162.0337], 
"April"=>[0.0, 8.3, 68.9331, 357.9168, 815.9662, 2870.217]
 }

Any ideas would be great, Thanks

like image 756
Hunter McMillen Avatar asked Aug 12 '11 13:08

Hunter McMillen


2 Answers

Ruby since version 1.9 (released dec 2007) maintains Hash order (see: http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/)

Also, there is a gem for this called orderedhash for older Rubies.

like image 200
Kimmo Lehto Avatar answered Oct 27 '22 22:10

Kimmo Lehto


You can keep a list on the side containing the keys in sorted order

initially:

hash = {}
keys = []

on insert:

def insert(key, value)
  keys << key unless hash[key]
  hash[key] = value
end

to iterate in insertion order:

for key in keys do
  puts key, hash[key]
end
like image 20
Paweł Obrok Avatar answered Oct 27 '22 23:10

Paweł Obrok