Methods with style
You know def – now come the finer points that make Ruby code readable. Keyword arguments make calls self-explaining, defaults make arguments optional:
def greet(name:, loud: false)
text = "Hello, #{name}"
loud ? text.upcase + "!" : text
end
greet(name: "Kaz", loud: true)Compare greet(name: "Kaz") with an anonymous greet("Kaz", true) – with several arguments the keyword variant clearly wins on readability. More conventions: *rest collects any number of arguments, methods ending in ? return true/false, methods ending in ! are the “dangerous” variant. And: the value of the last line is automatically the return value.
Remember lesson 22: parentheses are optional. Combined with keyword arguments this creates the declarative Ruby style you know from attr_reader :name – add_entry project: "X", from: "08:30", to: "10:00" reads almost like configuration. In nested expressions, though, the parentheses go back in.
timelog needs time math – "08:30" as hours since midnight:
def as_hours(time)
h, m = time.split(":").map(&:to_i)
h + m / 60.0
end
as_hours("08:30")add_entry(project:, from:, to:, note: nil). It returns a hash: { project:, from:, to:, note:, hours: }, where hours is the difference of as_hours(to) and as_hours(from). So add_entry(project: "X", from: "08:30", to: "10:00") should contain hours: 1.5.def as_hours(time)
h, m = time.split(":").map(&:to_i)
h + m / 60.0
end
# def add_entry(project:, from:, to:, note: nil)
# ...
# end