如何将哈希投射到ruby中的对象中?

时间:2013-07-22 20:22:17

标签: ruby mongoid

我正在使用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

1 个答案:

答案 0 :(得分:5)

根据源代码判断,看起来这正是TraitScore初始化方法的作用。

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