Translate

Saturday, 27 February 2016

Difference between Ruby’s Hash and ActiveSupport’s HashWithIndifferentAccess

  • HashWithIndifferentAccess allows us to access hash key as a symbol or string
  • Ruby hash allows us to access hash key as you defined in it.

Eg:- 

Ruby hash
2.1.0 :001 > hash = {a: 1, b:2}
 => {:a=>1, :b=>2} 
2.1.0 :002 > hash = {"a"=> 1, b:2}
 => {"a"=>1, :b=>2} 
2.1.0 :003 > hash["a"]
 => 1 
2.1.0 :004 > hash[:a]
 => nil 
2.1.0 :005 > hash[:b]
 => 2 

ActiveSupport::HashWithIndifferentAccess

2.1.0 :007 > require 'active_support/core_ext/hash/indifferent_access'
 => true 
2.1.0 :008 > hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1, b:2)
 => {"a"=>1, "b"=>2} 
2.1.0 :009 > hash[:a]
 => 1 
2.1.0 :010 >  hash["a"]
 => 1 
2.1.0 :011 > 


2 comments:

  1. Ruby Interview Questions and Answers
    http://allinterviewquestionsandanswerspdf.blogspot.in/2016/06/top-26-ruby-interview-questions-and.html

    ReplyDelete
  2. nice https://www.awrtechnologies.com

    ReplyDelete