Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Symbols vs Strings in Hashes

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?

like image 690
Rick Button Avatar asked Mar 15 '12 01:03

Rick Button


People also ask

What is difference between string and symbol in Ruby?

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.

Can hashes have symbols?

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.

Why are symbols faster than strings?

Symbols are immutable; Strings aren't. Being immutable means that the values won't change. Therefore, Symbols are faster than Strings.

What are symbols in Ruby?

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.


1 Answers

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/'
like image 167
Mark Thomas Avatar answered Sep 19 '22 05:09

Mark Thomas