2012-03-15 83 views
13

我有这个散列:红宝石VS符号中的字符串哈希

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

事实证明,

hash[:url] == nil 

hash['url'] == "http://feeds.washingtonpost.com/click.phdo?i=a67626ca64a9f1766b8ba425b9482d49" 

为什么?它是否不适用于?

回答

23

由于符号是不一样的来回转换两者之间一串:

:url == 'url' #=> false 

作为散列键他们会不同。也许你在Rails中看到过这种行为? Ruby on Rails使用HashWithIndifferentAccess,它将内容全部映射为字符串,因此您可以这样做:

h = HashWithIndifferentAccess.new 
h['url'] = 'http://www.google.com/' 
h[:url] #=> 'http://www.google.com/' 
+2

这是Rails。哦,与Ruby同时学习Rails的生活。 – 2012-03-15 01:45:52

+4

抱歉是迂腐,但HashWithInDifferentAccess其实只是检查密钥是否是一个符号,并强制进入一个字符串,如果是这样的话,而不是其他方式https://github.com/rails/rails/blob/3d6eafe32ed498784dba2b9782bbf7df47ebeb6b/activesupport /lib/active_support/hash_with_indifferent_access.rb#L152 – 2012-03-15 01:48:27

+0

好的。更新。 – 2012-03-15 19:50:16

2

为什么?---因为:url'url'是不同的,即:url != 'url'

它不应该与任何?---没有。

4

:url是一个Symbol这是比String'url'

> :ruby == "ruby­" 
=> false 

不同,您可以使用to_sto_sym

> "ruby".to_­sym 
=> :ruby 
> :ruby.to_s 
=> "ruby"