>
> What else you guys have in mind ?
Write some tests. Cover your edge cases. Make them pass.
Excellent suggestions.
> date = Date.today
> dates = [date]
What if the script is run on saturday?
Good pointer, I missed it.
Here is my modified code :
# date_helper.rb
require 'date'
def only_weekdays(start_date, n)
dates =
loop do
break if dates.size == n
dates << start_date if (1..5).include?(start_date.wday)
start_date += 1
end
dates
end
Spec for the method.
require_relative "../a.rb"
describe "#only_weekdays" do
context "when start_date is Sunday" do
let(:start_date) { Date.parse "22/02/2015" }
let(:week_days) { only_weekdays(start_date, 4) }
it "doesn't include Sunday" do
expect(week_days).not_to include(start_date)
end
it "returns 4 weekdays" do
expect(week_days.size).to eq(4)
end
end
context "when start_date is Saturday" do
let(:start_date) { Date.parse "21/02/2015" }
let(:weekends) { ["21/02/2015", "22/02/2015"].map(&Date.method(:parse)) }
let(:week_days) { only_weekdays(start_date, 4) }
it "excludes Saturday and Sunday" do
expect(week_days).not_to include(*weekends)
end
it "returns 4 weekdays" do
expect(week_days.size).to eq(4)
end
end
context "when start_date is Thrusday" do
let(:start_date) { Date.parse "19/02/2015" }
let(:weekends) { ["21/02/2015", "22/02/2015"].map(&Date.method(:parse)) }
let(:week_days) { only_weekdays(start_date, 4) }
it "excludes weekends" do
expect(week_days).not_to include(*weekends)
end
it "returns 4 weekdays" do
expect(week_days.size).to eq(4)
end
end
end
Result :
···
On Wednesday, February 25, 2015 12:38:36 PM Ryan Davis wrote:
> On Feb 25, 2015, at 11:19, Arup Rakshit <aruprakshit@rocketmail.com> wrote:
====
[arup@Ruby]$ rspec spec/a_spec.rb
......
Finished in 0.01237 seconds (files took 0.84944 seconds to load)
6 examples, 0 failures
[arup@Ruby]$
I'll be looking for some other solutions to the problem.
Again thanks to Ryan.
--
Regards,
Arup Rakshit
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.
--Brian Kernighan