Skip to content

Instantly share code, notes, and snippets.

@eladmeidar
Last active December 15, 2015 22:50
Show Gist options
  • Save eladmeidar/5336294 to your computer and use it in GitHub Desktop.
Save eladmeidar/5336294 to your computer and use it in GitHub Desktop.
java hash code in ruby
class String
def java_hash_code
size = self.size
hash = 0
self.chars.each_with_index do |ch, i|
hash += 31 * ch.ord ** (size - (i + 1))
end
[hash].pack("L")
end
end
puts 'Hello World'.java_hash_code
@dongqs
Copy link

dongqs commented Sep 10, 2014

This returns same result as java hashCode() does

TWO_31 = 2 ** 31
TWO_32 = 2 ** 32

def java_hash_code(str)
  size = str.size
  hash = 0
  str.chars.each_with_index do |ch, i|
    hash += ch.ord * (31 ** (size-(i+1)))
    hash = hash % TWO_32 - TWO_31
  end
  hash
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment