On Mon, 20 Mar 2006, Tanaka Akira wrote:

> Why we have no such method in the digest library?
>
> I think it is useful enough to have in the library.

indeed.  in fact this seems a good candidate to add a method to a base class:


     harp:~ > cat a.rb
     require 'digest/md5'
     require 'digest/rmd160'
     require 'digest/sha1'
     require 'digest/sha2'

     #
     # this in digest.rb or something equiv
     #
       digests = %w( MD5 RMD160 SHA1 SHA256 SHA384 SHA512 )

       digests.each do |d|
         digest_method = d.downcase

         IO.module_eval do
           define_method(digest_method) do |*argv|
             bufsize = argv.shift || 8192
             digest = ::Digest.const_get(d).new
             buf = ''
             off = pos rescue nil
             begin
               digest.update buf while read bufsize, buf
             ensure
               seek off rescue nil
             end
             digest
           end
         end

         File.module_eval do
           singleton_class = class << self; self; end
           singleton_class.module_eval do
             define_method(digest_method) do |path, *argv|
               mode = argv.shift || 'r'
               open(path, mode){|f| f.send digest_method}
             end
           end
         end
       end


     #
     # demo
     #
       report = {}
       digests.each do |d|
         digest_method = d.downcase
         report.update "File##{ digest_method}" => open(__FILE__){|f| f.send(digest_method).hexdigest}
         report.update "File.#{ digest_method}" => File.send(digest_method, __FILE__).hexdigest
       end
       require 'yaml' and y report



     harp:~ > ruby a.rb
     ---
     File.md5: 2e6c1e1c3d81a871f2c6b5099ba208f3
     File#md5: 2e6c1e1c3d81a871f2c6b5099ba208f3
     File.rmd160: 22ad54cb48f6d00ef325f1c7ff2150cf46fd250f
     File#rmd160: 22ad54cb48f6d00ef325f1c7ff2150cf46fd250f
     File.sha1: 1600889b027ced6bf95dedc9803cb7c65f5aa396
     File#sha1: 1600889b027ced6bf95dedc9803cb7c65f5aa396
     File.sha256: 38ac0f761f16a13d2f4f51a8a8c9668656d84c29b383840579a7517b69d219a9
     File#sha256: 38ac0f761f16a13d2f4f51a8a8c9668656d84c29b383840579a7517b69d219a9
     File.sha384: 5882c884ea618539da50a36bfbbd0fa0cd41bfa2ee18bce5acf45965e5582e33a1a3edd269f0e3551a9c9e5cd6e77cd1
     File#sha384: 5882c884ea618539da50a36bfbbd0fa0cd41bfa2ee18bce5acf45965e5582e33a1a3edd269f0e3551a9c9e5cd6e77cd1
     File.sha512: 3fba99ff4d98feaf760b814e9a8f245e05881da9aa19378510172d4e7cb0a10aa98b6c1d9b22d4331f3552a5899bb5545c604dfc4620665a5b6fb0d4dc2b0b78
     File#sha512: 3fba99ff4d98feaf760b814e9a8f245e05881da9aa19378510172d4e7cb0a10aa98b6c1d9b22d4331f3552a5899bb5545c604dfc4620665a5b6fb0d4dc2b0b78



comments?

-a
-- 
share your knowledge.  it's a way to achieve immortality.
- h.h. the 14th dali lama