Take the 2-minute tour ×

Suppose I have some lookup table, q(w, x, y, z), where various combination of keys map to different values; i.e., q(0, 0, 0, 0) = a, q(0, 0, 0, 1) = b, q(15, 16, 23, "b") = c.

What's the best way to implement this structure in Ruby in terms of efficiency? The keys will be generated dynamically and will generally be strings. I can think of three different keying methods with hashes:

  1. Use a string as the key: q["a, b, c, d"] = 0
  2. Use a single array as the key: q[["a", "b", "c", "d"]] = 0
  3. Use a hash of hashes: q["a"]["b"]["c"]["d"] = 0

I'm currently using method 2, and it's a little slower than I would like. These key combinations are generated dynamically—if I were to use a hash that takes a single string, will string concatenation be faster? Should I have started with a hash of hashes in the first place? Will this method take more space in memory?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

I would opt for something like your #1: create a single string which will then act as your map key. However ensure that your 'surrogate hash key' will be appropriately unique for various combinations of values. In this case you only have to build a simple string and need a single map.

Generally speaking you want map keys to be as immutable as possible. (A key mutating could mess up the table). Sometimes messy in Ruby since strings are mutable but still a worthwhile goal.

share|improve this answer

Your Answer


