Check for ruby ​​lost in the morning or afternoon

How can I print morning if Time.new is morning and noon if its day

00:00 - 12:00

12:00 - 00:00

+3
source share
3 answers

Another possibility if you will do this test a lot (not that I am a supporter of fixing the monkey when the hat falls):

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

puts Time.now.morning? ? 'morning' : 'afternoon'
+9
source

How about this:

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

This is equivalent to:

if Time.now.hour < 12
  puts 'morning'
else
  puts 'afternoon'
end
+6
source
(0..11).include?(Time.now.hour) ? 'morning' : 'afternoon'
+6
source

All Articles