[英]How do I cast a Hash into an object in ruby?
我正在使用Mongo,並將哈希存儲在數據庫中。 但是,稍后在檢索哈希時,不能再使用對象方法了嗎? 如何將從數據庫中檢索到的哈希值轉換為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
從源代碼來看,這正是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.