Ruby符号与哈希中的字符串

Ric*_*ton 13 ruby string hash symbols

我有这个哈希:

{
  "title"=>"Navy to place breath-test machines on all its ships", 
  "url"=>"http://feeds.washingtonpost.com/click.phdo?i=a67626ca64a9f1766b8ba425b9482d49"
} 
Run Code Online (Sandbox Code Playgroud)

事实证明

hash[:url] == nil
Run Code Online (Sandbox Code Playgroud)

hash['url'] == "http://feeds.washingtonpost.com/click.phdo?i=a67626ca64a9f1766b8ba425b9482d49"
Run Code Online (Sandbox Code Playgroud)

为什么?它不应该兼有吗?

Mar*_*mas 23

由于符号与字符串不同:

:url == 'url' #=> false
Run Code Online (Sandbox Code Playgroud)

作为哈希键,它们会有所不同.也许你在Rails中看到过这种行为?Ruby on Rails使用HashWithIndifferentAccess,它在内部将所有内容映射到String,因此您可以这样做:

h = HashWithIndifferentAccess.new
h['url'] = 'http://www.google.com/'
h[:url] #=> 'http://www.google.com/'
Run Code Online (Sandbox Code Playgroud)

  • 对不起,是迂腐,但HashWithInDifferentAccess实际上只是检查,如果关键是一个符号,在强制转换为一个字符串,如果是这样的话,而不是相反https://github.com/rails/rails/blob/3d6eafe32ed498784dba2b9782bbf7df47ebeb6b/activesupport/其他方式LIB/active_support/hash_with_indifferent_access.rb#L152 (4认同)
  • 这是Rails.哦,与Ruby同时学习Rails的生活. (2认同)