I have a big String with numbers 1-31. and how would i be able to center the name of the month?
My code:
class Month
attr_reader :month, :year
def
The String class in Ruby has a center method:
weekdays = "Su Mo Tu We Th Fr Sa"
month = "#{month_names} #{year}"
output = [
month.center(weekdays.size),
weekdays
].join("\n")
puts output
# April 2015
# Su Mo Tu We Th Fr Sa
The following does not really answer your question. It is just a complete rewrite of your code, because I was bored:
require 'date'
class Month
attr_reader :month, :year
def initialize(month, year)
@month = month
@year = year
end
def first_of_month
Date.new(year, month, 1)
end
def last_of_month
Date.new(year, month, -1)
end
def month_name
last_of_month.strftime('%B')
end
def days_in_month
last_of_month.day
end
def to_s
[].tap do |out|
out << header
out << weekdays
grouped_days.each do |days|
out << days.map { |day| day.to_s.rjust(2) }.join(' ')
end
end.join("\n")
end
private
def header
"#{month_name} #{year}".center(weekdays.size)
end
def weekdays
'Su Mo Tu We Th Fr Sa'
end
def grouped_days
days = (1..days_in_month).to_a
first_of_month.wday.times { days.unshift(nil) }
days.each_slice(7)
end
end
Month.new(4, 2015).to_s
# April 2015
# Su Mo Tu We Th Fr Sa
# 1 2 3 4
# 5 6 7 8 9 10 11
# 12 13 14 15 16 17 18
# 19 20 21 22 23 24 25
# 26 27 28 29 30