为什么Ruby将FixNum n散列为2n + 1? [英] Why does Ruby hash a FixNum n to 2n+1?

查看:111
本文介绍了为什么Ruby将FixNum n散列为2n + 1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Ruby将一个整数 n 转换为 2 * n + 1

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

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

我可以看到,你并不总是需要复杂的哈希,特别是对于简单的对象。但是为什么'double和add 1'规则与Python做的不同,就是把整数散列到自己的地方?

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]

是否有原因?

推荐答案

整数是对象,所以它们有一个object_id。但是有无数的整数。看似没有其他物体的空间。 Ruby如何解决这个问题?

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

整数采用所有奇怪的object_id,剩下的对象在两者之间,他们使用偶数。从object_id(和散列)到整数(反之亦然)的转换非常简单:砍掉最右边的1位(或添加它)。

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将FixNum n散列为2n + 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆