1

我正在使用 Mongo 并将哈希存储在数据库中。但是后来当我检索哈希时,我不能再使用我的对象方法了?如何将检索到的 Hash 从数据库中转换为 TraitScore ???

class TraitScore < Hash
  def initialize(attrs = {}, options = nil)
    self['net']    = attrs[:net]   || 0.0
    self['total']  = attrs[:total] || 0.0
    self['score']  = attrs[:score] || 0.0
  end

  def inc_net(val)
    self['net'] += val
  end

  def inc_total(val)
    self['total'] += (val || 0).abs
  end

  def set_score(score)
    self['score'] = score
  end
end
4

1 回答 1

5

从源代码来看,这似乎正是TraitScoreinitialize 方法的作用。

irb(main):001:0> hash = {net: 0.0, total: 5, score: 7}
=> {:net=>0.0, :total=>5, :score=>7}
irb(main):002:0> hash.class
=> Hash
irb(main):003:0> object = TraitScore.new(hash)
=> {"net"=>0.0, "total"=>5, "score"=>7}
irb(main):004:0> object.class
=> TraitScore
于 2013-07-22T20:43:34.140 回答