Ruby 的 Hash 和 ActiveSupport 的 HashWithIndifferentAccess 之间的区别

Difference between Ruby’s Hash and ActiveSupport’s HashWithIndifferentAccess

Ruby 的 Hash 和 ActiveSupport 的 HashWithIndifferentAccess 有什么区别?哪个最适合动态哈希?

在 Ruby 哈希中:

hash[:key]
hash["key"]

不同。顾名思义,在 HashWithIndifferentAccess 中,您可以通过任何一种方式访问​​ key

引用官方documentation对此:

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

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"]

下面的简单示例将向您展示简单 ruby 哈希与 "ActiveSupport::HashWithIndifferentAccess"

之间的区别
  • HashWithIndifferentAccess 允许我们以符号或字符串的形式访问哈希键

简单Ruby哈希

$ 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 继承自 ruby "Hash" 并在其中添加了以上特殊行为。