Ruby Symbols vs Strings in Hashes

前端 未结 3 490
甜味超标
甜味超标 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/'
    
    0 讨论(0)
  • 2020-12-31 08:25

    :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"
    
    0 讨论(0)
  • 2020-12-31 08:31

    Why?---Because :url and 'url' are different, i.e., :url != 'url'.

    Shouldn't it work with either?---No.

    0 讨论(0)
提交回复
热议问题