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/'
:url
is a Symbol which is different than the String 'url'
> :ruby == "ruby"
=> false
You can convert back and forth between the two using to_s
and to_sym
> "ruby".to_sym
=> :ruby
> :ruby.to_s
=> "ruby"
Why?---Because :url
and 'url'
are different, i.e., :url != 'url'
.
Shouldn't it work with either?---No.