Created
August 22, 2013 20:06
-
-
Save samullen/6312118 to your computer and use it in GitHub Desktop.
Wanting opinions on the each method. Am I doing this right?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
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.
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
Slightly unrelated to you requesting feedback on the "each" portion, but I think you want
attr_readerinstead ofattr_accessor. You're passing in start_time and end_time in the constructor, and likely want those attributes immutable after object instantiation.