Ruby符号与哈希中的字符串
我有这个杂烩:Ruby符号与哈希中的字符串,ruby,string,hash,symbols,Ruby,String,Hash,Symbols,我有这个杂烩: { "title"=>"Navy to place breath-test machines on all its ships", "url"=>"http://feeds.washingtonpost.com/click.phdo?i=a67626ca64a9f1766b8ba425b9482d49" } 原来 hash[:url] == nil 及 为什么??它不应该与这两个选项一起工作吗?为什么?---因为:url和'url'是不同的,即:url
{
"title"=>"Navy to place breath-test machines on all its ships",
"url"=>"http://feeds.washingtonpost.com/click.phdo?i=a67626ca64a9f1766b8ba425b9482d49"
}
原来
hash[:url] == nil
及
为什么??它不应该与这两个选项一起工作吗?为什么?---因为:url
和'url'
是不同的,即:url!='url'
它不应该与任何一个一起工作吗?---不。:url
是一个不同于'url'
> :ruby == "ruby"
=> false
您可以使用到_s
和到_sym
> "ruby".to_sym
=> :ruby
> :ruby.to_s
=> "ruby"
由于符号与字符串不同:
:url == 'url' #=> false
作为散列键,它们会有所不同。也许您在Rails中见过这种行为?Ruby on Rails使用它在内部将所有内容映射到字符串,因此您可以执行以下操作:
h = HashWithIndifferentAccess.new
h['url'] = 'http://www.google.com/'
h[:url] #=> 'http://www.google.com/'
是Rails。哦,与Ruby同时学习Rails的生活。很抱歉,这太迂腐了,但是HashWithUnderferenceAccess实际上只是检查键是否是一个符号,如果是这样的话,就强制输入一个字符串,而不是反过来
h = HashWithIndifferentAccess.new
h['url'] = 'http://www.google.com/'
h[:url] #=> 'http://www.google.com/'