我有一个从数据库中检索到的哈希值:
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
reshape
做的...就是正确的方式! :-)into
、as
、chain
、apply
,它有许多名称,但它是一个常见的抽象。http://stackoverflow.com/questions/5010828/something-like-let-in-ruby。https://dev59.com/-2nWa4cB1Zd3GeqP1H6a - tokland