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?
What is the difference between a symbol and a string? A string, in Ruby, is a mutable series of characters or bytes. Symbols, on the other hand, are immutable values. Just like the integer 2 is a value.
Hash's keySymbols are a good use for hash keys because they are immutable. You can't change a symbol once its defined. Only one copy of a symbol can exist at one time, so they do not consume a lot of memory. These two reasons makes symbols as keys faster than strings as keys.
Symbols are immutable; Strings aren't. Being immutable means that the values won't change. Therefore, Symbols are faster than Strings.
Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.
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/'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With