Ruby Symbols vs Strings in Hashes

前端 未结 3 491
甜味超标
甜味超标 2020-12-31 08:19

I have this hash:

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


        
3条回答
  •  自闭症患者
    2020-12-31 08:20

    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/'
    

提交回复
热议问题