在 Ruby 中检查是上午还是下午

4
如何在 Time.new 是早上时打印 "morning",而在下午时打印 "afternoon"?

00:00 - 12:00

12:00 - 00:00

4个回答

11

如果你将会频繁地进行这个测试(我并不是在鼓励一有机会就随意修改代码),还有另外一个可能性:

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

puts Time.now.morning? ? 'morning' : 'afternoon'

8
(0..11).include?(Time.now.hour) ? 'morning' : 'afternoon'

6
这个怎么样:
puts Time.now.hour < 12 ? 'morning' : 'afternoon'

这相当于:

if Time.now.hour < 12
  puts 'morning'
else
  puts 'afternoon'
end

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接