patternrubyMinor
Formatting a possibly nil value as hours and minutes
Viewed 0 times
formattingminuteshourspossiblyvalueniland
Problem
This might be a bit silly because there are like a thousand ways to do this, but I'm struggling to come up with one that I like. I feel like this should fit in one line, but I don't like re-using read_attribute(:length) lots and I don't like the below because it's not that clear.
# returns a human-readable string in the format Xh Ym
def length
# length stored in seconds
len = read_attribute(:length)
"#{(len/60/60).floor}h #{len.modulo(60*60)/60}m" unless len.nil?
endSolution
In one line
If
def length
(len = read_attribute(:length)) && "#{(len/60/60).floor}h #{len.modulo(60*60)/60}m"
endIf
len == nil return nil, if not - second operandCode Snippets
def length
(len = read_attribute(:length)) && "#{(len/60/60).floor}h #{len.modulo(60*60)/60}m"
endContext
StackExchange Code Review Q#1855, answer score: 6
Revisions (0)
No revisions yet.