From hash to class
Hashes are great to start with – but as soon as data needs behavior (computing hours, printing itself nicely), a class is the right home. We build timelog around two classes: Entry (one entry) and Timesheet (the collection).
class Entry
attr_reader :project, :from, :to, :note
def initialize(project:, from:, to:, note: nil)
@project = project
@from = from
@to = to
@note = note
end
def hours
as_hours(@to) - as_hours(@from)
end
def to_s
"#{@project}: #{@from}-#{@to} (#{hours}h)"
end
private
def as_hours(time)
h, m = time.split(":").map(&:to_i)
h + m / 60.0
end
end
Entry.new(project: "ProjectX", from: "08:30", to: "12:00").to_sNote: as_hours is private – an internal detail nobody outside needs. to_s decides how the object prints as text. Instance variables (@project) belong to the object; constants (BIG) to the class. Class variables (@@…) and globals ($…) are best avoided – shared state that's hard to trace.
class Timesheet
def initialize
@entries = []
end
def add(entry)
@entries << entry
self
end
def count
@entries.length
end
end
sheet = Timesheet.new
sheet.add(Entry.new(project: "ProjectX", from: "08:30", to: "12:00"))
sheet.countThe self at the end of add enables chaining: sheet.add(a).add(b).
Look it up: Visibility: private · to_s
Task: Extend
Timesheet with total_for(project): the total hours of all entries for that project. Use select and sum on @entries.# Entry from the demo cell above is reused here -
# run it first!
class Timesheet
def initialize
@entries = []
end
def add(entry)
@entries << entry
self
end
# def total_for(project)
# ...
# end
end