0

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.

Community
  • 1
  • 1
Howard
  • 19,215
  • 35
  • 112
  • 184

3 Answers3

2

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.

Neil Slater
  • 26,512
  • 6
  • 76
  • 94
0

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.

000
  • 26,951
  • 10
  • 71
  • 101
  • This is not an answer to the question. The concatenation case is just an example that the OP came up with where using a string key may (or may not) be useful. Pointing out that it is not useful in that particular case is missing the point of the question. The question is: When would be using a string key useful? This answer is discussing a totally irrelevant thing. – sawa Mar 26 '13 at 14:40
  • I think your standards are unreasonably high. – 000 Mar 26 '13 at 14:41
0

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.

000
  • 26,951
  • 10
  • 71
  • 101