Skip to content

Instantly share code, notes, and snippets.

@samullen
Created August 22, 2013 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save samullen/6312118 to your computer and use it in GitHub Desktop.
Save samullen/6312118 to your computer and use it in GitHub Desktop.
Wanting opinions on the each method. Am I doing this right?
class Timeframe
include Enumerable
attr_accessor :start_time, :end_time
ONEDAY = 24 * 60 * 60
def initialize(start_time, end_time)
@start_time = start_time
@end_time = end_time
end
def each
@current_time = @start_time
while @current_time <= @end_time
yield @current_time
@current_time += ONEDAY
end
end
end
@KellyMahan
Copy link

the code will work, but "each" doesn't really explain the method well enough.
Since you are wanting to yield each day, at what time each day?
The beginning of each day?
Same time every day from the start_time?
An equal amount of time for each instance so that each instance >= 1 day and < 2 days?

In the case of this method my 2nd question is what will be returned. But if the end time of the day is earlier than the start then that day won't be iterated.

@johnkary
Copy link

Slightly unrelated to you requesting feedback on the "each" portion, but I think you want attr_reader instead of attr_accessor. You're passing in start_time and end_time in the constructor, and likely want those attributes immutable after object instantiation.

@KellyMahan
Copy link

you may find this more useful

require 'date'
.
.
.
.
.
def each_day
(@start_time.to_date..@end_time.to_date).to_a.each do |date|
yield date
end
end

of course this returns the date object only and not a time object.

@samullen
Copy link
Author

@johnkary I'm just in the lazy habit of using attr_accessor. I'm a horrible person.

@KellyMahan The #each method is a special method used by the Enumerable module. When you define each in a class in which Enumerable has been included, you get instant access to most of Enumerable's methods (in this case, I wanted map).

But you're right, each_day would be much better, and so I think changing the name of the class might make each make a little more sense. I may change it to Daterange or Dayrange. Not sure.

Really appreciate the feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment