I wish to write one method to work with all classes in Digest::Base without repeatedly writing the same code.
def setup(file, hash_type)
# hash_type could be MD5, SHA1, SHA256, etc.
Digest::hash_type.new
Hash the file.
end
The above example is what I'd like to be able to do, but it does not work. I cannot insert 'hash_type' into the method in this manner. Trying to do so produces errors. I can do a bunch of conditionals like this:
def setup(file, hash_type)
if hash_type == MD5
Digest::MD5.new
Hash the file.
elsif hash_type == RMD160
Digest::RMD160.new
Hash the file.
else....
....
end
But then, I begin repeating myself. Any tips on making this work with fewer lines of code?
def hash_file(file, hash_kind)
digest = Digest.const_get(hash_kind.to_s.upcase).new
open(file, 'rb') do |f|
while (chunk = f.read(1))
digest.update(chunk)
end
end
digest
end
def hash_file(file, hash_kind)
digest = Digest.const_get(hash_kind.to_s.upcase).new
open(file, 'rb') do |f|
while (chunk = f.read(1))
digest.update(chunk)
end
end
digest
end