Given that using a symbol as a hash key is great according to this post, when do you need to use a string as a hash key?
Key concatenation, e.g.
hash["name" + "xxx"]
may be one such case, but I think the need is rare.
Even key concatenation can be converted easily:
hash[ ("name" + "xxx").to_sym ]
The short answer is that you benefit from avoiding using strings as keys in Ruby where the keys are just semantic labels to enable you to refer the values in code. In that case, it is clear that symbols do that job more efficiently (well, as pointed out above, provided you are not performing many conversions to generate the labels).
When you are parsing arbitrary data, e.g. XMl or JSON, then strings as keys might be more natural way of expressing the structure. Again, amount of conversion time from strings emitted by a parser into labels could be a factor.
If you're executing hash["name"+"xxx"]
many times in a loop, then it can be beneficial to pull the key out of the loop and turn it into a symbol. It's just a performance thing. Symbols use a single location in memory, but strings get computed every time they're created.
If you have a .yaml file that looks like this:
- thing1: value1
thing2: value2
thing3: value3
- thing1: value1
thing2: value2
thing3: value3
- thing1: value1
thing2: value2
thing3: value3
and you load it with YAML::load_file('filename')
, then you will need to use strings for keys.
However, if your yaml file looks like this:
- :thing1: value1
:thing2: value2
:thing3: value3
- :thing1: value1
:thing2: value2
:thing3: value3
- :thing1: value1
:thing2: value2
:thing3: value3
Then you can use symbols for keys. Symbols in this case are preferred for the ruby side, but the yaml would be cleaner with strings.