Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between hash and hashwithindifferent Acess

    • 0
    • 1
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 1.01k
    Comment on it

    The Hash class in Rubys core library retrieves values by doing a standard == comparison on the keys. This means that a value stored for a Symbol key (e.g. :my_value) cannot be retrieved using the equivalent String (e.g. my_value). On the other hand, HashWithIndifferentAccess treats Symbol keys and String keys as equivalent so that the following would work:

    rgb = ActiveSupport::HashWithIndifferentAccess.new
    rgb[:black] = '#000000'
    rgb[:black]  # => '#000000'
    rgb['black'] # => '#000000'

    If we check the object id of rgb[:black] and rgb['black'] it will be same. But for a hash the object id of :my_value and my_value will not be same and thus their value will also not be same.

    Another example of hashwithindifferentaccess is the params hash of rails framework.

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: