This is a card in Dave's Virtual Box of Cards.
Ruby's Hashes Guarantee Order
Created: 2024-03-30
Back to ruby
This card is a reminder to myself that, yes, Ruby does guarantee the order of Hash members!
This has been true since Ruby 1.9.
From Programming Ruby 3.3 (page 582) by Noel Rappin:
"…the order of the hash is consistent and based on the order in which the key/value pairs were added to the hash."
In other words, if you insert A and then B, you’re guaranteed to always get A before B.
Example:
foo = Hash.new foo['A'] = 1 foo['B'] = 2 foo.each {|k,v| puts "#{k} = #{v}"}
Always produces:
A = 1 B = 2
To quote Matz himself in 2018:
"Today, everyone knows Ruby’s Hash is a[n] OrderedHash."
Hopefully after writing this card, I’ll finally "know" it too!