ruby 42 lines · 8 steps

Counting business days in Ruby

A small calculator that skips weekends and holidays to count and add working days between dates.

Explained by highlit
1require 'date'
2require 'set'
3 
4class BusinessDayCalculator
5 DEFAULT_HOLIDAYS = Set[
6 Date.new(2024, 1, 1),
7 Date.new(2024, 7, 4),
8 Date.new(2024, 12, 25)
9 ].freeze
10 
11 def initialize(holidays: DEFAULT_HOLIDAYS)
12 @holidays = holidays.to_set
13 end
14 
15 def between(start_date, end_date)
16 start_date, end_date = end_date, start_date if start_date > end_date
17 
18 (start_date...end_date).count { |date| business_day?(date) }
19 end
20 
21 def add(start_date, days)
22 date = start_date
23 remaining = days
24 
25 while remaining > 0
26 date += 1
27 remaining -= 1 if business_day?(date)
28 end
29 
30 date
31 end
32 
33 def business_day?(date)
34 !weekend?(date) && !@holidays.include?(date)
35 end
36 
37 private
38 
39 def weekend?(date)
40 date.saturday? || date.sunday?
41 end
42end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A frozen Set of holidays gives fast membership checks and a safe, shared default.
  2. 2Swapping arguments up front lets one method handle either date order cleanly.
  3. 3Building higher-level operations on one small predicate keeps the logic consistent and testable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Counting business days in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code