Over a million developers have joined DZone.

Ruby: Hash ordering

DZone's Guide to

Ruby: Hash ordering

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

The application that I'm working on at the moment is deployed into production on JRuby but we also use the C Ruby 1.8.7 interpreter when developing locally since this allows us much quicker feedback.

As a result we sometimes come across interesting differences in the way that the two runtimes work.

One that we noticed yesterday is that if you create a hash, the order of the keys in the hash will be preserved when interpreted on JRuby but not with the C Ruby interpreter.

For example if we create the following hash in Ruby 1.8.7 it will be resorted into alphabetical order:

ruby-1.8.7 > a_hash = { :a => 1, :d => 2, :c => 3 }
 => {:a=>1, :c=>3, :d=>2}

Whereas in JRuby it will maintain its order:

jruby-1.5.1 > a_hash = { :a => 1, :d => 2, :c => 3 }
 => {:a=>1, :d=>2, :c=>3}

We found a post on the Ruby mailing list from a couple of years ago which pointed out that from Ruby 1.9 the order is in fact maintained.

However, Gregory Seidman also pointed out that…

Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays. Yes, this is a pet peeve of mine.

Since that is indeed what we want we've created an array of arrays in our code instead. The code to retrieve values from the array of arrays is a bit more verbose but at least the order is now guaranteed!

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.


Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}