我有从数据库中检索的这个哈希:
original_hash = {
:name => "Luka",
:school => {
:id => "123",
:name => "Ieperman"
},
:testScores => [0.8, 0.5, 0.4, 0.9]
}
我正在编写一个 API,并希望向客户端返回一个稍微不同的哈希:
result = {
:name => "Luka",
:schoolName => "Ieperman",
:averageScore => 0.65
}
这不起作用,因为该方法reshape
不存在。它是否以另一个名字存在?
result = original_hash.reshape do |hash|
{
:name => hash[:name],
:school => hash[:school][:name],
:averageScore => hash[:testScores].reduce(:+).to_f / hash[:testScores].count
}
end
我是 Ruby 的新手,所以我想在我开始重写核心类之前先问一下。我确信它一定存在,因为我在编写 API 时总是发现自己在重塑哈希值。还是我完全错过了什么?
实现非常简单,但是,就像我说的,如果我不需要,我不想覆盖 Hash:
class Hash
def reshape
yield(self)
end
end
顺便说一句,我知道这一点:
result = {
:name => original_hash[:name],
:school => original_hash[:school][:name],
:averageScore => original_hash[:testScores].reduce(:+).to_f / original_hash[:testScores].count
}
但有时我没有original_hash
变量,而是直接根据返回值进行操作,或者我在一个班轮中,这种基于块的方法很方便。
真实世界的例子:
#get the relevant user settings from the database, and reshape the hash into the form we want
settings = users.find_one({:_id => oid(a[:userID])}, {:emailNotifications => 1, :newsletter => 1, :defaultSocialNetwork => 1}).reshape do |hash|
{
:emailNotifications => hash[:emailNotifications] == 1,
:newsletter => hash[:newsletter] == 1,
:defaultSocialNetwork => hash[:defaultSocialNetwork]
}
end rescue fail