我有一个表示秒的浮点数。所以,我可以有38.93秒。如果可能的话,我正在寻找“最干净”的方式来获得时间,如果不可能的话,我会寻找分钟,如果几分钟和几小时都不可能。当我说可能时,我的意思是:
如果小于3600秒,则为分钟或秒。如果少于60秒,则为秒。
现在我做了几个,如果看看它应该是什么,但我想可能必须有一个更清洁的方式。
if input > 3600
return input/3600, 'hours'
elseif input < 3600 && input > 60
return input/60, 'minutes'
else
return input, 'seconds'
由于
答案 0 :(得分:5)
恕我直言,范围的案例陈述会更清晰:
def some_method_name(input)
case input
when 0...60
input, 'seconds'
when 60...3600
input/60, 'minutes'
else
input/3600, 'hours'
end
end
另一种方法是首先提取小时,分钟和秒:
def some_method_name(input)
hours, seconds = input.divmod(3600)
minutes, seconds = seconds.divmod(60)
if hours > 0
hours, 'hours'
elsif minutes > 0
minutes, 'minutes'
else
seconds, 'seconds'
end
end
在Rails中,您当然会使用内置pluralization。
答案 1 :(得分:1)
这种方法的优点是能够灵活地指定所需的单位间隔。如果你愿意,可以很容易地添加几周,大约几个月,几年。它还修复了奇异值的复数化。
TimeInt = Struct.new :name, :secs
INTERVALS = [ TimeInt[:days, 60*60*24], TimeInt[:hours, 60*60],
TimeInt[:minutes, 60], TimeInt[:seconds, 1] ]
def time_with_adaptive_units(secs)
ti = INTERVALS.find { |ti| secs >= ti.secs } || INTERVALS.last
val, name = (secs.to_f/ti.secs).round, ti.name.to_s
name.sub!(/s$/,'') if val == 1
"#{val} #{name}"
end
[5] pry(main)> time_with_adaptive_units(1)
=> "1 second"
[6] pry(main)> time_with_adaptive_units(45)
=> "45 seconds"
[7] pry(main)> time_with_adaptive_units(450)
=> "7 minutes"
[8] pry(main)> time_with_adaptive_units(4500)
=> "1 hour"
[9] pry(main)> time_with_adaptive_units(45000)
=> "12 hours"
[10] pry(main)> time_with_adaptive_units(450000)
=> "5 days"
答案 2 :(得分:0)
我能想到的是:
total_seconds = 23456
intervals = [3600, 60, 1].inject({rem: total_seconds, parts:[]}) do |memo, factor|
count = (memo[:rem] / factor).floor
memo[:rem] = memo[:rem] - (count * factor)
memo[:parts] << count
memo
end
你可以用
来完成它itervals[:parts].zip(['hours', 'minutes', 'seconds']).map{|p| p.join(' ')}.join(', ')
您还可以看到,如果您想要将其扩展到数天,数周,数月,数年,数十年和数百年,这是微不足道的:D
答案 3 :(得分:-1)
input = 4000 #input in seconds
h = {(60..3599) => ["input/60",'Minutes'], (0..59) => ["input",'Seconds'],(3600..Float::INFINITY) => ["input/3600",'Hours']}
h.each_pair {|k,v| p "#{v.last} is #{eval(v.first)}" if k.include? input}
input = 1100 #input in seconds
h = {(60..3599) => ["input/60",'Minutes'], (0..59) => ["input",'Seconds'],(3600..Float::INFINITY) => ["input/3600",'Hours']}
h.each_pair {|k,v| p "#{v.last} is #{eval(v.first)}" if k.include? input}
input = 14 #input in seconds
h = {(60..3599) => ["input/60",'Minutes'], (0..59) => ["input",'Seconds'],(3600..Float::INFINITY) => ["input/3600",'Hours']}
h.each_pair {|k,v| p "#{v.last} is #{eval(v.first)}" if k.include? input}
输出:
"Hours is 1"
"Minutes is 18"
"Seconds is 14"