Pages

Sunday, February 11, 2018

Ruby’s Hash Vs ActiveSupport’s HashWithIndifferentAccess


The Hash class in Ruby’s core library retrieves values by doing a standard == comparison on the keys. This means that a value stored for a Symbol key (e.g. :some_value) cannot be retrieved using the equivalent String (e.g. ‘some_value’). 
On the other hand, class HashWithIndifferentAccess is inherited from ruby "Hash" & a special behavior is added in it. HashWithIndifferentAccess treats Symbol keys and String keys as equivalent so that the following would work:

h = HashWithIndifferentAccess.new
h[:my_value] = 'foo'
h['my_value'] #=> will return "foo"


Lets discuss this in more details:

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

Ruby Hash


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

ActiveSupport::HashWithIndifferentAccess

>> hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1, b:2)
 => {"a"=>1, "b"=>2} 
> hash[:a]
 => 1 
> hash["a"]
 => 1 

1 comment:

  1. This is a very nice article. thank you for publishing this. i can understand this easily.!!.Ruby on Rails Online Training Hyderabad

    ReplyDelete