下面的代碼有助於計算完成任務的工作時間。在calculate_deadline
方法,在BusinesHours類,兩個把報表揭示這一ruby:自己從一個班級變爲另一個班級
puts self
#<BusinessHours:0x000001008cbb70>
puts self[start_time.to_date].inspect
#<TimeRange:0x000001008cbb48 @range=2010-06-10 09:00:00 -0700..2010-06-10 15:00:00 -0700>
我不明白,爲什麼在calculate_deadline把「自我」旁邊start_time.to_date改變來自BusinessHours類自我TIMERANGE類,如兩個puts語句表明,特別是因爲'to_date'方法是Time類的一部分。你能解釋這是怎麼發生的嗎?
require 'time'
require 'date'
class Time
def to_date
Date.new(year, month, day)
end
end
class BusinessHours
def initialize(time_in, time_out)
@default_range = TimeRange.new(time_in, time_out)
@modified_days = {}
end
def update(day, time_in, time_out)
key = day.is_a?(Symbol) ? day : Date.parse(day)
@modified_days.merge!({key => TimeRange.new(time_in, time_out)})
end
def closed(*days)
days.each {|day| update(day, '0:00', '0:00')}
end
def [](date)
day_of_week = date.strftime("%a").downcase.to_sym
range = @modified_days[date] || @modified_days[day_of_week] || @default_range
# reset time range dates to match date param
range.reset_date(date)
range
end
def calculate_deadline(seconds, start_time)
start_time = Time.parse(start_time)
puts self
puts self[start_time.to_date].inspect
range = self[start_time.to_date]
if range.applies?(start_time)
start_time = [start_time, range.start].max
available_seconds = range.stop - start_time
return start_time + seconds if available_seconds > seconds
seconds -= available_seconds
end
calculate_deadline(seconds, (start_time.to_date + 1).to_s)
end
end
class TimeRange
def initialize(time_in, time_out)
@range = Time.parse(time_in)..Time.parse(time_out)
end
def reset_date(date)
@range = Time.local(date.year, date.month, date.day, start.hour, start.min)..
Time.local(date.year, date.month, date.day, stop.hour, stop.min)
end
def applies?(time)
stop > time
end
def stop
@range.end
end
def start
@range.begin
end
end
k = BusinessHours.new("9:00 AM", "3:00 PM")
k.calculate_deadline(20*60*60, "Jun 7, 2010 10:45 AM")
非常感謝您的明確解釋。我絆倒了方法[](日期) – BrainLikeADullPencil
這是Ruby中定義的一種特殊語法,但它只是一種像其他任何方法一樣的實例方法。 – bricker
因此實際上是[](日期)方法的日期參數在括號內:[start_time.to_date] – BrainLikeADullPencil