Why does Ruby hash a FixNum n to 2n+1?

2019-02-18 05:50发布

问题:

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

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

I can see that you don't always need to have complicated hashes, especially for simple objects. But why the 'double and add 1' rule as opposed to doing what Python does, which is to hash integers to themselves?

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

Is there a reason?

回答1:

Integers are objects, so they have an object_id. But there is an infinite number of integers. Seemingly, no room for other objects. How does Ruby pull this off?

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

Output:

1
3
5
7
9
11
13
15
17
19

Integers take all odd object_id's, the rest of the objects go in between, they use the even numbers. The conversion from object_id (and hash) to integer (and vice versa) is very easy: chop the rightmost 1 bit (or add it).



标签: ruby hash