如何使用 Ruby 生成 Java 的 String hashCode

foo*_*mes 1 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

Ung*_*gue 5

这是我的版本。它的作用与 javascript hashCode 相同。注意 32 位转换技巧打包和解包:

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