如何使用Ruby生成Java的String hashCode [英] How to generate Java's String hashCode using Ruby

查看:225
本文介绍了如何使用Ruby生成Java的String hashCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Ruby中生成与Java的String.hashCode方法返回的哈希码相同的哈希码.哪种方法最优雅? Java的String hashCode实现的描述如下: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#hashCode%28%29

I want to generate, in Ruby, the same hash code returned by Java's String.hashCode method. What approach would be most elegant? Java's String hashCode implementation is described here: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#hashCode%28%29

推荐答案

这是我的版本.它与javascript hashCode相同. 请注意32位转换技巧的打包和解压缩:

This is my version. It does the same as javascript hashCode. Note the 32 bit conversion trick packing and unpacking:

  def hash_code(str)
    str.each_char.reduce(0) do |result, char|
      [((result << 5) - result) + char.ord].pack('L').unpack('l').first
    end
  end

这篇关于如何使用Ruby生成Java的String hashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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