Ruby符号与Hashes中的字符串 [英] Ruby Symbols vs Strings in Hashes

查看:111
本文介绍了Ruby符号与Hashes中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个散列:

  {
title=>海军进行呼气测试所有船只上的机器,
url=>http://feeds.washingtonpost.com/click.php?id=a67626ca64a9f1766b8ba425b9482d49
}



$ b $ p



$ hash [ :url] == nil

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

为什么?它不应该与它一起工作吗?

解决方案

由于符号与字符串不同:

 :url =='url'#=>假

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

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


I have this hash:

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

It turns out that

hash[:url] == nil

and

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

Why? Shouldn't it work with either?

解决方案

Since a symbol is not the same as a string:

:url == 'url' #=> false

As hash keys they would be different. Perhaps you have seen this behavior in Rails? Ruby on Rails uses HashWithIndifferentAccess which maps everything to a String internally, so you can do this:

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

这篇关于Ruby符号与Hashes中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆