Creating an md5 hash of a number, string, array, or hash in Ruby

前端 未结 5 1652
轻奢々
轻奢々 2021-02-01 13:13

I need to create a signature string for a variable in Ruby, where the variable can be a number, a string, a hash, or an array. The hash values and array elements can also be any

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 14:05

    Just my 2 cents:

    module Ext
      module Hash
        module InstanceMethods
          # Return a string suitable for generating content signature.
          # Signature image does not depend on order of keys.
          #
          #   {:a => 1, :b => 2}.signature_image == {:b => 2, :a => 1}.signature_image                  # => true
          #   {{:a => 1, :b => 2} => 3}.signature_image == {{:b => 2, :a => 1} => 3}.signature_image    # => true
          #   etc.
          #
          # NOTE: Signature images of identical content generated under different versions of Ruby are NOT GUARANTEED to be identical.
          def signature_image
            # Store normalized key-value pairs here.
            ar = []
    
            each do |k, v|
              ar << [
                k.is_a?(::Hash) ? k.signature_image : [k.class.to_s, k.inspect].join(":"),
                v.is_a?(::Hash) ? v.signature_image : [v.class.to_s, v.inspect].join(":"),
              ]
            end
    
            ar.sort.inspect
          end
        end
      end
    end
    
    class Hash    #:nodoc:
      include Ext::Hash::InstanceMethods
    end
    

提交回复
热议问题