.hash字符串方法如何工作? [英] how .hash string method work?

查看:147
本文介绍了.hash字符串方法如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是一个红宝石新手。我见过一个字符串方法(String).hash。



例如,在 irb 中,我试过了

 >> mgpyone.hash 

退货

  => 144611910 

此方法如何工作?

解决方案

为所有对象定义散列方法。请参阅文档


为此
对象生成一个 Fixnum 散列值。此函数必须具有
属性 a.eql?(b)意味着 a.hash == b.hash
散列值由类 Hash 使用。
超过 Fixnum 的容量的任何散列值将在使用前截断


所以 String.hash 方法在 C-Code 。基本上(过于简化)它只是总结该字符串中的字符。


I'm just a newbie to ruby. I've seen a string method (String).hash .

For example, in irb, I've tried

>> "mgpyone".hash

returns

=> 144611910

how does this method works ?

解决方案

The hash method is defined for all objects. See documentation:

Generates a Fixnum hash value for this object. This function must have the property that a.eql?(b) implies a.hash == b.hash. The hash value is used by class Hash. Any hash value that exceeds the capacity of a Fixnum will be truncated before being used.

So the String.hash method is defined in C-Code. Basically (over-simplified) it just sums up the characters in that string.

这篇关于.hash字符串方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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