データベースから取得した次のハッシュがあります。
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