bodo
bodo

Reputation: 847

Why do String hashes change?

I have this code:

class DocumentIdentifier
  attr_reader :folder, :name

  def initialize( folder, name )
    @folder = folder
    @name = name
  end

  def ==(other)
    return true if other.equal?(self)
    return false unless other.kind_of?(self.class)
    folder == other.folder && name == other.name
  end

  def hash
    folder.hash ^ name.hash
  end

  def eql?(other)
    return false unless other.instance_of?(self.class)
    other.folder == folder && other.name == name
  end
end

first_id = DocumentIdentifier.new('secret/plans', 'raygun.txt')
puts first_id.hash

Why is the hash code changing for each call?

I think it should remain the same as a String hash code in Java. Or, the hashcode is changing because every call gives me new instances of folder and name? Ruby's String type has an implementation of the hash method, so the same String should give me the same number for each call.

Upvotes: 0

Views: 329

Answers (1)

Dogbert
Dogbert

Reputation: 222148

Same string doesn't return same hash between two sessions of Ruby, only in the current session.

➜  tmp  pry
[1] pry(main)> "foo".hash
=> -3172192351909719463
[2] pry(main)> exit
➜  tmp  pry
[1] pry(main)> "foo".hash
=> 2138900251898429379
[2] pry(main)> "foo".hash
=> 2138900251898429379

Upvotes: 7

Related Questions