1

I need to determine the current time of day and let the user know it's time to do a particular task. For example if the time is between an amount of hours (eg. Between 6am and 12pm) the user should do a certain task. If the time is after that (between 1pm and 6pm) the user should do another task and if the time is any time outside those times they should do something else.

I don't know enough about ruby to post an example of code I've worked on so far. All I know is how to determine what the current time is with t = Time.now and how to determine if the time is between certain hrs, what I don't know is how to put that in a method to determine if the hrs are between a given time to tell the user to perform the task.

Any help appreciated.

Vic Alfieri
  • 25
  • 2
  • 12

4 Answers4

2

First of all, get acquainted with usage of Time class in ruby.

As you get comfortable with it, you'll see that making comparisons like below is simple enough.

2.3.1 :001 > n = Time.now.hour
 => 17 
2.3.1 :002 > n.between? 13, 18 #1 pm - 6 pm
 => true 
2.3.1 :004 > n.between? 6, 12
 => false 

Note: between comes from Comparable module

you can start by playing with below snippet.

2.3.1 :001 > def task_for_night
2.3.1 :002?>   puts "night task started"
2.3.1 :003?>   end
 => :task_for_night 
2.3.1 :004 > def task_for_day
2.3.1 :005?>   puts "day time"
2.3.1 :006?>   end
2.3.1 :021 > def assign_task
2.3.1 :022?>   (Time.now.hour.between? 6,12) ? task_for_night : task_for_day
2.3.1 :023?>   end
 => :assign_task 
2.3.1 :024 > assign_task
day time
 => nil 
marmeladze
  • 6,468
  • 3
  • 24
  • 45
1

case with ranges is the perfect syntax for what you want to do :

case Time.now.hour
when (6..12)
  puts "Task A"
when (13..18)
  puts "Task B"
else
  puts "Free time"
end
Community
  • 1
  • 1
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
0

Get current time (only hour: %H) and convert it to integer.

time = Time.now.strftime('%H').to_i
# 15

And check condition of time in nested ternary operator (conditional operator)

(time.between? 6,12) ? "Do morning's task" : (time.between? 13,18) ? "Do afternoon's task" : "Do something else"

# Do afternoon's task
Abhishek28
  • 57
  • 6
  • No. `time` is not a time, it's an hour. No need to convert from time to string to int, just use `Time.now.hour`. Finally, don't use double ternaries, it's pretty hard to read. – Eric Duminil Feb 27 '17 at 14:13
0

Also you can use #case :

def what_should_i_do_now?
  case Time.now.hour
  when 6..12 then 'Do morning task'
  when 13..18 then "Do afternoon's task"
  else "Do something else"
  end
end

and now you can do even more:

def what_should_i_do_at(time)
  case time.hour
  when 6..12 then 'Do morning task'
  when 13..18 then "Do afternoon's task"
  else "Do something else"
  end
end

> what_should_i_do_at(Time.now+60*60) # plus 1 hour
#=> "Do afternoon's task" 
Oleksandr Holubenko
  • 4,310
  • 2
  • 14
  • 28