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

时间:2015-08-08 07:28:23

标签: ruby-on-rails ruby hash activesupport

Ruby的Hash和ActiveSupport的HashWithIndifferentAccess之间有什么区别?动态哈希哪个最好?

2 个答案:

答案 0 :(得分:22)

下面是一个简单的例子,它将向您展示简单的 ruby​​ hash& “ActiveSupport :: HashWithIndifferentAccess”

  • 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 
  • class HashWithIndifferentAccess继承自ruby“Hash”&amp;上面添加了特殊行为。

答案 1 :(得分:4)

在Ruby Hash中:

hash[:key]
hash["key"]

是不同的。在HashWithIndifferentAccess顾名思义,您可以访问key

引用官方documentation

  

实现一个哈希,其中键:foo和“foo”被认为是   相同。

  

内部符号在用作键时用于映射到字符串   整个书写界面(调用[] =,合并等)。这种映射   属于公共接口。例如,给定:

     

hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)

     

你是   保证密钥以字符串形式返回:

     

hash.keys # => ["a"]