Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Ruby’s Hash and ActiveSupport’s HashWithIndifferentAccess

Tags:

What is the difference between Ruby’s Hash and ActiveSupport’s HashWithIndifferentAccess? Which is the best for dynamic hashes?

like image 988
Bibek Sharma Avatar asked Aug 08 '15 07:08

Bibek Sharma


2 Answers

Below is the simple example that will show you difference between simple ruby hash & a "ActiveSupport::HashWithIndifferentAccess"

  • HashWithIndifferentAccess allows us to access hash key as a symbol or string

Simple Ruby Hash

$ irb   2.2.1 :001 > hash = {a: 1, b:2}     => {:a=>1, :b=>2}    2.2.1 :002 > hash[:a]     => 1    2.2.1 :003 > hash["a"]     => nil  

ActiveSupport::HashWithIndifferentAccess

2.2.1 :006 >   hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1, b:2) NameError: uninitialized constant ActiveSupport     from (irb):6     from /home/synerzip/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>' 2.2.1 :007 > require 'active_support/core_ext/hash/indifferent_access'  => true  2.2.1 :008 > hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1, b:2)  => {"a"=>1, "b"=>2}  2.2.1 :009 > hash[:a]  => 1  2.2.1 :010 > hash["a"]  => 1  
  • class HashWithIndifferentAccess is inherited from ruby "Hash" & above special behavior is added in it.
like image 172
Pratik Avatar answered Oct 04 '22 02:10

Pratik


In Ruby Hash:

hash[:key] hash["key"] 

are different. In HashWithIndifferentAccess as the name suggests, you can access key either way.

Quoting official documentation to this:

Implements a hash where keys :foo and "foo" are considered to be the same.

and

Internally symbols are mapped to strings when used as keys in the entire writing interface (calling []=, merge, etc). This mapping belongs to the public interface. For example, given:

hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)

You are guaranteed that the key is returned as a string:

hash.keys # => ["a"]

like image 37
shivam Avatar answered Oct 04 '22 01:10

shivam