Ruby的Hash
和ActiveSupport的HashWithIndifferentAccess
之间有什么区别?动态哈希哪个最好?
答案 0 :(得分:22)
下面是一个简单的例子,它将向您展示简单的 ruby hash& “ActiveSupport :: HashWithIndifferentAccess”
简单的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
答案 1 :(得分:4)
在Ruby Hash中:
hash[:key]
hash["key"]
是不同的。在HashWithIndifferentAccess
顾名思义,您可以访问key
。
引用官方documentation:
实现一个哈希,其中键:foo和“foo”被认为是 相同。
和
内部符号在用作键时用于映射到字符串 整个书写界面(调用[] =,合并等)。这种映射 属于公共接口。例如,给定:
hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
你是 保证密钥以字符串形式返回:
hash.keys # => ["a"]