2012-03-15 95 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"