4

如果 Time.new 是上午,如果是下午,我如何打印上午

00:00 - 12:00

12:00 - 00:00

4

4 回答 4

11

如果您将经常进行此测试,则另一种可能性(不是我提倡随意修补猴子):

class Time
  def morning?
    hour < 12
  end
  def afternoon?
    hour >= 12
  end
end

puts Time.now.morning? ? 'morning' : 'afternoon'
于 2012-04-17T08:53:58.160 回答
7
(0..11).include?(Time.now.hour) ? 'morning' : 'afternoon'
于 2012-04-17T08:52:00.467 回答
6

这个怎么样:

puts Time.now.hour < 12 ? 'morning' : 'afternoon'

这相当于:

if Time.now.hour < 12
  puts 'morning'
else
  puts 'afternoon'
end
于 2012-04-17T08:49:49.057 回答
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)
于 2020-04-12T18:54:52.013 回答