Last Updated: February 25, 2016
·
1.523K
· Tamer Shlash

Symbolized Hash With Indifferent Access

Today, I've published a new gem called symbolized, which is basically a duplicate of ActiveSupport's HashWithIndifferentAccess, but instead of storing keys internally as strings, they're stored as symbols.

Why would I want that?

That's particularly useful when you have a large number of hashes that share the same keys, and it may become inefficient to keep all these identical keys as strings. An example of this case is when you have data processing pipelines that process millions of hashes with the same keys.

How can it be used?

Here's a snippet that demonstrates the basics:

require 'symbolized'

# You can create a SymbolizedHash directly:

symbolized_hash = SymbolizedHash.new
symbolized_hash['a'] = 'b'
symbolized_hash['a'] #=> 'b'
symbolized_hash[:a]  #=> 'b'
symbolized_hash.keys #=> [:a]

# Or initialize it with a normal hash:

symbolized_hash = SymbolizedHash.new({'a' => 'b'})
symbolized_hash['a'] #=> 'b'
symbolized_hash[:a]  #=> 'b'
symbolized_hash.keys #=> [:a]

# Or use the Hash#to_symbolized_hash core extension:

h = { 'a' => 'b' }
h['a'] #=> 'b'
h[:a]  #=> nil
h.keys #=> ['a']

symbolized_hash = h.to_symbolized_hash
symbolized_hash['a'] #=> 'b'
symbolized_hash[:a]  #=> 'b'
symbolized_hash.keys #=> [:a]

Where can I learn more about it?

You can get more details about the gem at the github repository:
https://github.com/TamerShlash/symbolized