如果Time.new是早上和下午,如果下午
,我该如何打印早晨00:00 - 12:00
12:00 - 00:00
答案 0 :(得分:10)
另一种可能性,如果你将经常进行这项测试(不是我主张用一顶帽子修补猴子):
class Time
def morning?
hour < 12
end
def afternoon?
hour >= 12
end
end
puts Time.now.morning? ? 'morning' : 'afternoon'
答案 1 :(得分:6)
这个怎么样:
puts Time.now.hour < 12 ? 'morning' : 'afternoon'
这相当于:
if Time.now.hour < 12
puts 'morning'
else
puts 'afternoon'
end
答案 2 :(得分:6)
(0..11).include?(Time.now.hour) ? 'morning' : 'afternoon'
答案 3 :(得分:0)
def get_time_of_day(hour)
if (hour >= 5 and hour <= 9)
return "early_morning"
elsif (hour > 9 and hour <= 11)
return "late morning"
elsif (hour > 11 and hour <= 13)
return "early afternoon"
elsif (hour > 13 and hour <= 16)
return "late afternoon"
elsif (hour > 16 and hour <= 19)
return "evening"
end
end
# example call
get_time_of_day(DateTime.now.hour)