Progetto timelog – si parte!
Da qui in poi costruiamo insieme un programma vero: timelog, un registro delle ore. Cresce un po' in ogni lezione – finché interpreta le voci, calcola report, è completamente testato e ha persino un'interfaccia web.
Cominciamo dalla forma dei dati. Una voce di tempo ha un progetto e delle ore – come hash. Tante voci – come array di hash:
entries = [
{ project: "ProjectX", hours: 3.5 },
{ project: "Intern", hours: 2.0 },
{ project: "ProjectX", hours: 3.0 }
]
entries.lengthOra i metodi delle collezioni mostrano la loro forza. map estrae valori, select filtra, sum somma – e tutto si può concatenare:
entries.select { |e| e[:project] == "ProjectX" }
.sum { |e| e[:hours] }La star dei report è group_by: smista gli elementi in un hash di gruppi. Insieme a transform_values diventa un report completo in due righe:
entries.group_by { |e| e[:project] }Utili anche: tally conta le occorrenze, sort_by ordina, each_with_object costruisce strutture di ogni tipo.
hours a partire da entries, che associ a ogni progetto il suo totale di ore: {"ProjectX"=>6.5, "Intern"=>2.0}. Suggerimento: group_by + transform_values.entries = [
{ project: "ProjectX", hours: 3.5 },
{ project: "Intern", hours: 2.0 },
{ project: "ProjectX", hours: 3.0 }
]
# hours = ...