wackyburkay wackyburkay - 1 year ago 76
Ruby Question

How to add a value to an existing hash without a key

I need to assign the numbers 0-100000 to a hash without giving a key.

Ruby uses Murmur as hash function. How can I add a value without having a key, like in C, letting it handle collision and other things. Is it possible? Can I give just the value to hash and let it evaluate the key, then insert to itself?

In a normal hashing operation, we have a hash function, and a table. We use value as the argument of the hash function, then we get a key in return. The value is inserted to the key location in the table (if a collision happens, double hashing or something else used).

Is it possible to do the same type of hashing in Ruby? Or am I stuck with default ways? Can I just throw the value into a function, then it evaluates the key, and inserts the value to the hash table or not?

Answer Source

The common solution is to simply use the value as a key. Hence:

value = "xxx"
hash[value] = 1

This way, you clearly document that the actual values (all 1) of this particular hash are of no use, and you will get de-duplicated values. Hash will do the usual hashing internally, you don't need to worry about it at all.

I use 1 as value here, but the actual value is completely irrelevant. I don't use nil as that is the default return value of hash[nonexistant_value].

If your values are more complex, check out http://docs.ruby-lang.org/en/2.0.0/Hash.html for specifics about them.