5
\$\begingroup\$

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?
end
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Apr 13, 2011 at 9:44
\$\endgroup\$
0

3 Answers 3

6
\$\begingroup\$

In one line

def length
 (len = read_attribute(:length)) && "#{(len/60/60).floor}h #{len.modulo(60*60)/60}m"
end

If len == nil return nil, if not - second operand

answered Apr 13, 2011 at 18:56
\$\endgroup\$
4
\$\begingroup\$

One-liners are nice, but sometimes it's better just to split lines. For example:

def length
 if (len = read_attribute(:length))
 "#{(len/60/60).floor}h #{len.modulo(60*60)/60}m" 
 end
end

If you really like compact code that deals with nil values, you can work with the idea of maybe's ick:

def length
 read_attribute(:length).maybe { |len| "#{(len/60/60).floor}h #{len.modulo(60*60)/60}m" }
end
answered Apr 23, 2011 at 22:13
\$\endgroup\$
2
\$\begingroup\$

Assuming that len is an integer you won't need to use floor. You can do something like this

"#{len/3600}h #{(len/60) % 60}m" unless len.nil?
answered Apr 13, 2011 at 15:19
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.