Why does Ruby hash have FixNum n up to 2n + 1?

Why does a Ruby hash have an integer n up to 2 * n + 1 ?

 >> [0,1,2,3].each {|x| puts x.hash} 1 3 5 7 

I see that you do not always need complex hashes, especially for simple objects. But why is the "double and add 1" rule unlike what Python does, which is an integer number of hashes for itself?

 >>> map(hash,[0,1,2,3]) [0, 1, 2, 3] 

Is there a reason?

+4
source share
1 answer

Integers are objects, so they have an object_id. But there is an infinite number of integers. There seems to be no room for other objects. How did Ruby get it out?

 10.times{|i| puts i.object_id} 

Output:

 1 3 5 7 9 11 13 15 17 19 

Whole elements take all the odd objects object_id, the rest of the objects go between them, they use even numbers. Converting from object_id (and hash) to integer (and vice versa) is very simple: slice the rightmost 1 bit (or add it).

+5
source

Source: https://habr.com/ru/post/1395675/


All Articles