h = { foo: 'bar' }
puts h[:foo]
puts h['foo']In Ruby, a hash with symbol keys does not recognize string keys as the same. So h[:foo] returns 'bar', but h['foo'] returns nil.
Symbols are immutable and reused internally, so using them as hash keys saves memory and can improve performance compared to strings.
key = 'name' h = { key => 'Alice' } key << '!' puts h['name'] puts h['name!']
The hash key is the original string 'name'. Mutating the string variable after adding it as a key does not change the existing key in the hash. So h['name'] returns 'Alice', but h['name!'] returns nil.
h[:name] return nil?h = { 'name' => 'Bob' }
puts h[:name]The hash key is the string 'name', but the lookup uses the symbol :name. These are different keys in Ruby hashes, so h[:name] returns nil.
h = { foo: 1, 'bar' => 2, :baz => 3, 'qux' => 4 }The keys foo: and :baz are symbols. The keys 'bar' and 'qux' are strings. So there are 2 symbol keys.
