Project timelog – here we go!
From here on we build a real program together: timelog, a time tracker. It grows a little in every lesson – until it parses entries, computes reports, is fully tested and even has a web interface.
We start with the data shape. A time entry has a project and hours – as a hash. Many entries – as an array of hashes:
entries = [
{ project: "ProjectX", hours: 3.5 },
{ project: "Intern", hours: 2.0 },
{ project: "ProjectX", hours: 3.0 }
]
entries.lengthNow the collection methods show their power. map extracts values, select filters, sum adds up – and everything chains:
entries.select { |e| e[:project] == "ProjectX" }
.sum { |e| e[:hours] }The star for reports is group_by: it sorts elements into a hash of groups. Together with transform_values that becomes a complete report in two lines:
entries.group_by { |e| e[:project] }Also useful: tally counts occurrences, sort_by sorts, each_with_object builds arbitrary structures.
hours from entries that maps each project to its total hours: {"ProjectX"=>6.5, "Intern"=>2.0}. Hint: group_by + transform_values.entries = [
{ project: "ProjectX", hours: 3.5 },
{ project: "Intern", hours: 2.0 },
{ project: "ProjectX", hours: 3.0 }
]
# hours = ...