0

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.

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

6 Comments

Was on my way to say the same thing. I'd recommend the poster use Digest::SHA1 or an equivalent instead. See stackoverflow.com/questions/4452161/… for some related info.
Thank you for posting, automatically goes to my favorites questions
It's a security feature. If the hash would be predictable, a malevolent user could precompute lots of strings with the same hash and feed them to your app, hampering performance.
+1 @steenslag. That was an exploit seen against Hash types in other other languages for the same reason.
Ok I confused. How will Hash object figured out in which bucked has to find a key (suppose we use key which will be an object with implemented hash and eql? methods), when key is changing between each call. I suppose that Ruby doesn't function as Java, which load object into jvm, but create instances which only live during script execution.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.