简体   繁体   English

如何将哈希值投射到红宝石中的对象?

[英]How do I cast a Hash into an object in ruby?

I am using Mongo and storing a hash in the database. 我正在使用Mongo,并将哈希存储在数据库中。 However later on when I retrieve the hash, I can no longer use my object methods? 但是,稍后在检索哈希时,不能再使用对象方法了吗? How can I cast the retrieved Hash from the database into a TraitScore??? 如何将从数据库中检索到的哈希值转换为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

Judging by the source code, it looks like that's exactly what TraitScore 's initialize method does. 从源代码来看,这正是TraitScore的initialize方法所做的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM