Ruby Symbols vs Strings in Hashes

不羁的心 提交于 2019-11-30 08:49:56

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!