I need a hash algorithm while using Ruby. In my situation I'm comparing the contents of the file. I was using MD5, but it examines the filename as well (or seems to anyway). Is there an algorithm that I can easily implement or will I have to write one from scratch?
3 Answers
Use FileUtils.compare_file.
require 'fileutils'
FileUtils.compare_file('somefile', 'somefile') #=> true
1 Comment
Michael Kohl
Looking at the implementation of this, it compares the two file streams block wise and stops as soon the blocks don't match. Interesting method, didn't know it before.
I'm not sure why do you think it compares filename?
require "digest"
Digest::MD5.hexdigest(File.read('file1'))
=> "60b725f10c9c85c70d97880dfe8191b3"
Digest::MD5.hexdigest(File.read('file2'))
=> "60b725f10c9c85c70d97880dfe8191b3"
What did you do to get different checksums?
4 Comments
avatarmonkeykirby
Really? I used FileUtils.cp and it gave me different sums. It really doesn't make sense to me either.
Slartibartfast
@avatarmonkeykirby How do you mean cp?
compare_file returns true on those files as well. Maybe files in question are different (whitespace etc...)tokland
@avatarmonkeykirby: you should paste that code in the question.
avatarmonkeykirby
I used FileUtils.cp to copy the file and THEN compared the sums with MD5. This is probably a problem with my computer.