Ruby的Hash
和ActiveSupport的HashWithIndifferentAccess
有什麼區別?哪個是最適合動態哈希的?Ruby的哈希和ActiveSupport的Hash之間的區別WithIndifferentAccess
回答
下面是簡單的例子,會告訴你簡單的區別ruby hash & a「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」&以上的特殊行爲被添加進來。
在Ruby哈希:
hash[:key]
hash["key"]
是不同的。顧名思義,在HashWithIndifferentAccess
中,您可以以任何方式訪問key
。
引述官方documentation這樣:
實現,其中鍵的哈希:foo和 「富」 被認爲是 相同。
和
在內部作爲 整個寫入接口鍵(呼叫[] =,合併,等)一起使用時的符號被映射到的字符串。該映射 屬於公共接口。例如,給定:
hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
您是 保證關鍵是返回一個字符串:
hash.keys # => ["a"]
我認爲在HashWithIndifferentAccess的情況下,在整個寫入接口(調用[] =,merge等)中用作鍵時,符號被映射到字符串。這樣對嗎? –
是的。內部符號在整個寫入界面(調用[] =,合併等)中用作鍵時映射到字符串。該映射屬於公共接口。 – shivam
- 1. 一致哈希和錐哈希之間的區別是什麼?
- 2. ActiveSupport中mattr_accessor和cattr_accessor之間的區別?
- 3. set和hash之間的區別?
- 4. Oracle和tomcat md5哈希之間的區別?
- 5. 字典和哈希表之間的真正區別是什麼?
- 6. 哈希克爾派生和實例之間的區別
- 7. 哈希映射,哈希集合,哈希字典之間有什麼區別?
- 8. 找出哈希和數組之間的變量類別和區別
- 9. For和Ruby之間的區別
- 10. Ruby 1.8.6和1.8.7之間的區別?
- 11. Ruby中+和<<之間的區別
- 12. rubygem guard和grunt.js之間的區別?
- 13. powershell和ruby之間的區別
- 14. Ruby和C之間的主要區別
- 15. ruby和python之間的語法區別?
- 16. Ruby - 變量和@variable之間的區別
- 17. Perl中的哈希和哈希引用有什麼區別?
- 18. 在Perl中,if(%hash)和if(定義的%hash)之間有什麼區別?
- 19. Python和其他文件哈希之間的MD5哈希差異
- 20. 紅寶石/哈希:的ActiveSupport :: HashWithIndifferentAccess
- 21. bsddb:哈希格式,btree格式和記錄格式之間的區別
- 22. Laravel Un Hash哈希值?
- 23. '+ ='和'= +'之間的區別?
- 24. {!!之間的區別!!}和{{}}
- 25. ==和case之間的區別?
- 26. '#','%'和'$'之間的區別
- 27. | =和^ = css之間的區別
- 28. 「%〜dp0」和「。\」之間的區別?
- 29. .eq之間的區別。和==
- 30. ==和.equals()之間的區別?
完美的例子 –