How to generate a unique object hash based on the class attributes? How to generate a unique object hash based on the class attributes? sqlite sqlite

How to generate a unique object hash based on the class attributes?


require 'digest/md5'class Location  attr_accessor :name,     # string, default => :null                  :size,     # integer, default => 0                  :latitude, # float, default => 0                  :longitude # float, default => 0  # Returns a unique hash for the instance.  def hash    Digest::MD5.hexdigest(Marshal::dump(self))  endend

test with pry

[1] pry(main)> foo = Location.new;[2] pry(main)> foo.name = 'foo';[3] pry(main)> foo.size = 1;[4] pry(main)> foo.latitude = 12345;[5] pry(main)> foo.longitude = 54321;[6] pry(main)> [7] pry(main)> foo.hash=> "2044fd3756152f629fb92707cb9441ba"[8] pry(main)> [9] pry(main)> foo.size = 2=> 2[10] pry(main)> foo.hash=> "c600666b44eebe72510cc5133d8b4afb"

Or you could also create your customize function for serializing the properties. for example to use all of the instance variable

def hash  variables = instance_variables.map {|ivar| instance_variable_get(ivar)}.join("|separator|")  Digest::MD5.hexdigest(variables)end

or to select the one you need

def hash  variables = [name, size].join("|separator|")  Digest::MD5.hexdigest(variables)end