back home

Using symbols or strings for hash objects in Ruby?

[pawel@server Tumblr (master)]$ irb

irb(main):001:0> test = {“test” => “zxczxc”}

=> {“test”=>”zxczxc”}

irb(main):002:0> puts test[“test”]


=> nil

irb(main):003:0> puts test[:test]

=> nil

irb(main):004:0> test = {:test => “asdasd”}

=> {:test=>”asdasd”}

irb(main):005:0> puts test[“test”]

=> nil

irb(main):006:0> puts test[:test]


=> nil

This short irb session showed what’s broken with my ruby code. I didn’t know that when you have a hash with keys which are symbols you must not access them using strings, and other way around - having a hash with strings you must not refer to them using symbols. How broken is that?

You could assume that everything will be kept as symbol since they are immutable and mutating hash key is really a bad idea. But that comes with a price - symbols are never garbage collected.

Now, each library can decide whether to use symbols or strings. I see that on forums people advocate for using symbols. But Koala (Facebook client) uses strings and my code was broken because I assumed symbols.

I learned there’s a way to make the hash behave the same, you can call hash.with_indifferent_access which will return hash that will behave intuitively.