【问题标题】:How to generate a unique object hash based on the class attributes?如何根据类属性生成唯一的对象哈希?
【发布时间】:2013-07-16 21:33:04
【问题描述】:

我有一个具有不同属性的模型。并非每个实例的每个属性都有一个值。

class Location

  attr_accessible :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
   # ...
  end

end

如何实现一个散列函数,它返回一个实例的唯一 ID?每次我在对象上调用散列函数时,它都应该是相同的。我不想要一个随机的唯一 ID。应该可以将哈希存储在 sqlite3 数据库中而无需修改。


正如您在answer by MetaSkills 中看到的那样,重写 hash 方法不是一个好主意,因为它“被大量红宝石对象用于比较和相等"。因此我将其重命名为custom_attributes_hash

【问题讨论】:

    标签: ruby hash sqlite uniqueidentifier


    【解决方案1】:
    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))
      end
    
    end
    

    用撬来测试

    [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"
    

    或者您也可以创建自定义函数来序列化属性。例如使用所有的实例变量

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

    或者选择你需要的那个

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

    【讨论】:

    • 不错。有没有办法可以定义构建哈希所涉及的属性?
    猜你喜欢
    • 2011-07-30
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多