Skip to content

Instantly share code, notes, and snippets.

@Slackwise
Last active November 1, 2018 01:57
Show Gist options
  • Save Slackwise/d240453ddb5ec9b368a2213715a06a27 to your computer and use it in GitHub Desktop.
Save Slackwise/d240453ddb5ec9b368a2213715a06a27 to your computer and use it in GitHub Desktop.
Implemented `/usr/bin/cal` (sans opts) in Ruby as a fun challenge my friend mentioned doing in an interview.
#!/usr/bin/env ruby
require 'date'
today = Date.today
first_day = Date.new(today.year, today.month, 1)
last_day = Date.new(today.year, today.month, -1) # A trick from JavaScript, heh...
first_week_blank_count = first_day.wday
last_week_blank_count = last_day.wday
day_slots = Array.new(first_week_blank_count) + (first_day..last_day).to_a + Array.new(last_week_blank_count)
def highlight(str)
"\e[7m#{str}\e[27m"
end
week_str = day_slots.slice_after { |d| d && d.saturday? }.map { |week|
week.map { |date|
if date
date_str = date.day.to_s.rjust(2)
date == today ? highlight(date_str) : date_str
else
' '
end
}.join(' ')
}.join(?\n)
month_header = today.strftime('%B %Y').center(20)
day_header = 'Su Mo Tu We Th Fr Sa' # Should really be a CONSTANT, but also, should be localized...
puts month_header,
day_header,
week_str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment