rubyguides

Hash#store

Hash#store associates a value with a key in a hash. It is functionally identical to the bracket assignment syntax h[key] = value, but the method form makes the return value explicit: store returns the value that was just stored, not the hash.

Syntax

h.store(key, value) → value

Parameters

ParameterTypeDescription
keyObjectThe key to associate — can be any object
valueObjectThe value to associate with the key

Return Value

store returns the value that was stored — not the hash. This is different from languages like Python where dict[key] = value returns the value, but it matches Ruby’s bracket assignment which also returns the stored value.

h = {}
result = h.store(:name, "Alice")
result # => "Alice"

Examples

Basic usage

h = {}
h.store(:name, "Alice")
h.store(:age, 30)
h # => {:name=>"Alice", :age=>30}

Overwriting an existing key

h = {name: "Alice", age: 30}
h.store(:name, "Bob")
h # => {:name=>"Bob", :age=>30}

Chaining assignments

Because store returns the stored value, you can chain it:

h = {}
[h.store(:a, 1), h.store(:b, 2), h.store(:c, 3)]
# => [1, 2, 3]

With arbitrary key types

h = {}
h[[1, 2, 3]] = "array key"
h[[1, 2, 3]] # => "array key"

h[->() { 42 }] = "lambda key"
h[->() { 42 }] # => nil (each lambda is a different object)

nil as a key

h = {}
h[nil] = "null value"
h[nil] # => "null value"

store vs []

Both store and []= associate a key with a value. There is no functional difference.

h = {}

h[:key] = "value"     # => "value"
h.store(:key2, "val") # => "val"

h # => {:key=>"value", :key2=>"val"}

Choose store when you want the method call form to be explicit, or []= when bracket syntax feels more natural.

Gotchas

Mutating a key object breaks lookup

Using a mutable object as a key and then mutating it breaks hash lookups, because the key’s hash value changes:

h = {}
key = [1, 2]
h[key] = "value"

key << 3
h[key]     # => nil — hash of [1,2] changed
h[[1, 2]]  # => nil — no key with hash of [1,2] exists anymore

Always use immutable objects (symbols, strings, numbers, frozen arrays) as hash keys when possible.

String and symbol keys are distinct

h = {}
h["name"] = "Alice"
h[:name]  = "Bob"
h # => {"name"=>"Alice", :name=>"Bob"}
h["name"]  # => "Alice"
h[:name]   # => "Bob"

See Also