man ruby/hash
How Ruby's Hash works: st_table, open addressing and ar_table
What does {} turn into in Ruby, and how does it remember the order you put
things in?
counts = Hash.new(0)
words.each { |w| counts[w] += 1 }
counts.each { |word, n| puts "#{word} #{n}" } # first-seen order
This article reads the C source of ruby 4.0.10 (st.c, hash.c and
internal/hash.h) and checks it with small programs on an Apple M2 Pro, where ruby is Homebrew’s
/opt/homebrew/opt/ruby/bin/ruby 4.0.10. Every
number below comes from that source, Ruby’s release notes, or a program I ran.
The short version
A Hash has two representations. Up to 8 entries it is an ar_table, a flat
array of key/value pairs stored inside the Hash object itself, searched
linearly, with one byte of each key’s hash kept as a hint. From the ninth
entry on it is an st_table, an array of entries in insertion order. From
the seventeenth entry the st_table also gets a separate array of bins, an
open-addressing hash table whose slots hold indexes into the entries array. Iterating walks the entries array, which is
why order is insertion order.
The small form: ar_table
internal/hash.h defines the small form. Its size limit is
RHASH_AR_TABLE_MAX_SIZE, which is SIZEOF_VALUE: 8 on a 64-bit build.
typedef struct ar_table_struct {
union {
ar_hint_t ary[RHASH_AR_TABLE_MAX_SIZE];
VALUE word;
} ar_hint;
/* 64bit CPU: 8B * 2 * 8 = 128B */
ar_table_pair pairs[RHASH_AR_TABLE_MAX_SIZE];
} ar_table;
ar_hint_t is an unsigned char. So the 8 hints fit in one machine word,
followed by 8 key/value pairs. RHASH_AR_TABLE(h) returns the address just
past the struct RHash header, and hash_alloc_flags sizes the object as
sizeof(struct RHash) plus the table. There is no separate allocation.
The small form still hashes. ar_insert and ar_lookup both call
ar_do_hash(key), keep the low byte as the hint, and scan the occupied
entries. A full key comparison only happens where the hint byte matches
(ar_find_entry_hint). The one exception is a lookup in an empty hash, which
returns before hashing anything.
When a ninth key arrives, ar_insert returns -1 and ar_force_convert_table
builds an st_table. It hashes all existing keys again, because the hint kept
only one byte of each.
The large form: st_table
The comment at the top of st.c describes it with this picture (redrawn):
bins (open addressing) entries (insertion order)
+-----------+ 0 1 2
| 0 empty | +--------+--------+--------+-----
| 3 --------+----------------->| hash | hash | hash |
| 1 deleted | | key | key | key | ...
| 2 --------+---> entry 0 | record | record | record |
| 4 --------+---> entry 2 +--------+--------+--------+-----
| 0 empty | ^ entries_start ^ entries_bound
+-----------+
bin value = entry index + 2; 0 = empty, 1 = deleted
Each entry stores the full hash, the key and the value (record), 24 bytes
on a 64-bit build. New entries always go at entries_bound, the end of the
used part, so the array is in insertion order by construction.
The bins hold small integers. 0 means empty, 1 means “was used by a deleted
entry”, and anything else is an entry index plus 2 (ENTRY_BASE). The width
of a bin depends on the table size. The features[] table pairs each
entries size with a bin array twice as large, and picks 8-bit bins up to 128
entries, 16-bit up to 32,768, then 32-bit and 64-bit. A table of 100 entries
spends 1 byte per bin.
To find a key, hash_bin takes the low bits of the hash (the bin count is a
power of two). On a collision, secondary_hash computes the next bin:
*perturb >>= 11;
ind = (ind << 2) + ind + *perturb + 1;
return hash_bin(ind, tab);
perturb starts as the full hash and shifts 11 bits right each step, so the
high bits of the hash get a say. Once it reaches zero, the step is
ind = 5 * ind + 1 modulo a power of two. The comment cites the Hull-Dobell
theorem. With a = 5 and c = 1 that generator visits every bin, so a probe
always terminates.
Tables with 16 entries or fewer have no bins at all.
MAX_POWER2_FOR_TABLES_WITHOUT_BINS is 4, and st_init_existing_table_with_size
sets bins = NULL up to 2⁴ entries. Those tables search the entries array
linearly, like the small form, comparing the full stored hash before the key.
Watching it grow
ObjectSpace.memsize_of shows each step:
$ ruby -e 'require "objspace"; [0,1,8,9,16,17,32,33,64,65].each { |n| h = {}; n.times { |i| h[i] = i }; puts "#{n}: #{ObjectSpace.memsize_of(h)}" }'
0: 160
1: 160
8: 160
9: 544
16: 544
17: 992
32: 992
33: 1824
64: 1824
65: 3488
The arithmetic matches the source. 160 bytes is the object’s heap slot with the ar_table inside it. At 9 entries the table gets 16 entries of 24 bytes: 160 + 384 = 544, no bins. At 17 it gets 32 entries and 64 one-byte bins: 160 + 768 + 64 = 992. Each later doubling adds entries and bins in the same proportion.
Growth happens in rebuild_table, which runs when entries_bound reaches
the end of the array. If between a quarter and a half of the slots hold live
entries (the rest were deleted), it compacts the array in place. Otherwise it
allocates a table for 2 * num_entries - 1 entries, which rounds up to the
next power of two, and reinserts the live entries in order. Without
deletions that doubles the table. The stored hashes are reused, so no key is hashed again.
Deletion marks the entry with a reserved hash value and the bin as deleted.
Deleting the first entry just moves entries_start forward, which makes
Hash#shift cheap. Order survives all of this:
$ ruby -e 'h = { b: 1, a: 2, c: 3 }; h[:a] = 20; p h; h.delete(:b); h[:b] = 1; p h'
{b: 1, a: 20, c: 3}
{a: 20, c: 3, b: 1}
Updating a value leaves the key where it was. Deleting and reinserting puts it at the end.
Hashing integers
any_hash in hash.c sends small integers (T_FIXNUM) to rb_objid_hash,
which multiplies and mixes the value through key64_hash with two fixed
primes. The starting value comes from rb_hash_start, which adds a salt that
Init_RandomSeedCore fills with random bytes at startup. So integer hashes change between runs:
$ ruby -e 'p 57.hash, "57".hash'
-951122635581206060
-3785444003825680309
$ ruby -e 'p 57.hash, "57".hash'
-1906282008911847222
-628130618125344467
Iteration order doesn’t change, because it never depended on the hash. At
the end, any_hash clamps the result into the Fixnum range so it can be
returned as a Ruby Integer.
One lookup or two
counts[k] += 1 is counts[k] = counts[k] + 1. That is a lookup ([]) and
then an insert ([]=), each hashing the key. Enumerable#tally instead calls
rb_hash_stlike_update, which reaches st_update (or ar_update for a small
hash). Those hash the key once, find the slot, and let a callback change the
count in place. A key class that counts its #hash calls shows the
difference:
class Key
attr_reader :n
@@calls = 0
def self.calls = @@calls
def self.reset = @@calls = 0
def initialize(n) = @n = n
def hash
@@calls += 1
@n.hash
end
def eql?(other) = other.is_a?(Key) && n == other.n
end
keys = Array.new(1000) { |i| Key.new(i % 100) }
counts = Hash.new(0)
keys.each { |k| counts[k] += 1 }
puts "counts[k] += 1: #{Key.calls} calls to #hash"
Key.reset
keys.tally
puts "tally: #{Key.calls} calls to #hash"
$ ruby hashcalls.rb
counts[k] += 1: 2008 calls to #hash
tally: 1009 calls to #hash
With 8 distinct keys instead of 100, the hash never leaves the small form and the counts are 1999 and 1000. The first lookup hits an empty hash and skips hashing. The 9 extra calls with 100 keys come from the conversion at the ninth key. The first eight keys are hashed again, and the ninth is hashed once by the small table that rejects it and once by the new one.
Curious facts
A key that changes after insertion gets lost until you call
rehash, because its entry still holds the old hash:$ ruby -e 'a = [1]; h = { a => :x }; a << 2; p h[a]; h.rehash; p h[a]' nil :xHash.new(capacity: n)(Ruby 3.4) allocates the large form up front.Hash.new(capacity: 100)reports 3488 bytes before any insert, the same as a hash that grew to 65 entries.Hash.new(0)never stores the default. After readingh[5],h.sizeis still 0.The table can grow to 2⁵⁸ entries on a 64-bit build (
MAX_POWER2). Beyond thatget_power2raisesRuntimeErrorwith “st_table too big”.st.cstill opens with “This is a public domain general purpose hash table package originally written by Peter Moore @ UCB”, followed by Vladimir Makarov’s credit for the redesign. Its last paragraph claims the rewrite sped up Ruby’s hash benchmarks by over 40% on Intel Haswell.
History
- 1.9: “Hash preserves order. It enumerates its elements in the order in which the keys are inserted.” (NEWS-1.9.1)
- 2.4: “st_table (st.c) internal data structure is improved” (Feature
#12142). Makarov’s name appears in
st.cat v2_4_0 and not at v2_3_0. - 2.6:
ar_tableappears inhash.c(50 matches at v2_6_0, none at v2_5_0). - 2.7:
Enumerable#tally(Feature #11076). - 3.1:
tallyaccepts a hash to count into (Feature #17744). - 3.4:
Hash.newacceptscapacity:(Feature #19236).
Sources
All source links are at tag v4.0.10 (commit a704b7cd95), the build that
printed ruby 4.0.10 (2026-11-19 revision a704b7cd95) +PRISM [arm64-darwin27].
st.c: design comment,features[],MAX_POWER2_FOR_TABLES_WITHOUT_BINS, bin values,hash_bin,st_init_existing_table_with_size,rebuild_table,secondary_hash,st_insert,st_updateinclude/ruby/st.h:struct st_tableinternal/hash.h:RHASH_AR_TABLE_MAX_SIZEandar_table,RHASH_AR_TABLEhash.c:any_hash,key64_hashandrb_objid_hash,ar_do_hash,ar_find_entry_hint,ar_force_convert_table,ar_insertandar_lookup,hash_alloc_flags,rb_hash_stlike_update,rb_hash_aref, Entry Order documentationrandom.c:rb_hash_startand its random saltenum.c:tally_upandenum_tally- Release notes: NEWS-1.9.1, NEWS-2.4.0, NEWS-2.7.0, NEWS-3.1.0, NEWS-3.4.0
- Older tags checked by grep:
hash.cat v2_5_0,hash.cat v2_6_0,st.cat v2_3_0,st.cat v2_4_0
grep -rl /lib/ruby/hash/
ls ruby/
- draft How Ruby sorts: qsort_r, a private introsort and quickselectIn ruby 4.0.10, sort hands the work to the C library, sort_by on numbers runs its own introsort, and max_by(n) runs a quickselect. None of them promises stability.