14200 divided by 3600 is approximately 3.9, which in integer arithmetic is truncated to 3.
-14200 divided by 3600 is approximately -3.9, which in integer arithmetic is truncated to -4.
With %
, negatives "count backward" from the second value -- your results make perfect sense when you keep that in mind. For example:
1 % 6 # => 1
-1 % 6 # => 5
Update: I think you need to think about exactly what you want if the seconds are negative. You might do something like this:
dir = "from now"
if s < 0
dir = "ago"
s = -s
end
h = s / 3600
m = (s % 3600 ) / 60
puts "s represents #{h} hours and #{m} minutes #{dir}"
What to do really depends on exactly what h
and m
mean in the greater context of your code, and exactly what negative s
values mean in that context.
In another situation, maybe you want h
and m
to have the same absolute value as if s
was positive but with the same sign as s
:
sign = s < 0 ? -1 : 1
s = s.abs
h = s / 3600 * sign
m = (s % 3600 ) / 60 * sign
It's up to you to determine what is appropriate in your situation.