【发布时间】:2015-12-06 22:22:30
【问题描述】:
如何比我更优雅地总结所有哈希值?
boards_statistics 数组包含 items_info 哈希值。
def generate_accumulated_statistics(boards_statistics)
# Create hash with zero values - its purprose is to
# accumulate results from all other hashes
resulted_hash = {
items_info: {
finished_items: {
todo: 0,
in_progress: 0,
done: 0
},
hours_worked: {
estimated: 0,
time_logged: 0
},
story_points_completed: {
estimated: 0,
completed: 0
},
due_today_items: 0,
late_items: 0
},
team_info: []
}
boards_statistics.each do |statistics|
resulted_hash[:items_info][:finished_items][:todo] += statistics[:items_info][:finished_items][:todo]
resulted_hash[:items_info][:finished_items][:in_progress] += statistics[:items_info][:finished_items][:in_progress]
resulted_hash[:items_info][:finished_items][:done] += statistics[:items_info][:finished_items][:done]
resulted_hash[:items_info][:hours_worked][:estimated] += statistics[:items_info][:hours_worked][:estimated]
resulted_hash[:items_info][:hours_worked][:time_logged] += statistics[:items_info][:hours_worked][:time_logged]
resulted_hash[:items_info][:story_points_completed][:estimated] += statistics[:items_info][:story_points_completed][:estimated]
resulted_hash[:items_info][:story_points_completed][:completed] += statistics[:items_info][:story_points_completed][:completed]
resulted_hash[:items_info][:due_today_items] += statistics[:items_info][:due_today_items]
resulted_hash[:items_info][:late_items] += statistics[:items_info][:late_items]
end
end
【问题讨论】:
-
我投票结束这个问题作为题外话,因为询问如何做一些更优雅的工作是一个代码审查,属于Code Review而不是Stack Overflow,这是用于代码问题。
-
快速:
resulted_hash.to_s.scan(/=>\K\d+/).reduce(0) { |tot, s| tot + s.to_i } #=> 0。全部为零并不是最好的例子。 “result_hash”或“resulting_hash”会是一个更好的名字,因为“resulted”是一个动词。
标签: ruby algorithm ruby-on-rails-4 hash