如果 Time.new 是上午,如果是下午,我如何打印上午
00:00 - 12:00
12:00 - 00:00
如果您将经常进行此测试,则另一种可能性(不是我提倡随意修补猴子):
class Time
def morning?
hour < 12
end
def afternoon?
hour >= 12
end
end
puts Time.now.morning? ? 'morning' : 'afternoon'
(0..11).include?(Time.now.hour) ? 'morning' : 'afternoon'
这个怎么样:
puts Time.now.hour < 12 ? 'morning' : 'afternoon'
这相当于:
if Time.now.hour < 12
puts 'morning'
else
puts 'afternoon'
end
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)