ruby - How can I make the days of the month be printed according to each day (ex: Su Mo Tu We...etc)? -


i have big string numbers 1-31. , how able center name of month?

my code:

class month    attr_reader :month, :year    def initialize( month, year)     @month = month    @year = year   end    def month_names     names_of_months = {1 => 'january', 2 => 'february', 3 => 'march', 4 => 'april', 5 => 'may', 6 => 'june', 7 => 'july', 8 => 'august', 9 => 'september', 10 => 'october', 11 => 'november', 12 => 'december'}    return names_of_months[@month]   end    def length    days_of_months  = {1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30, 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31}     return days_of_months[@month]   end    def to_s    output = "#{month_names} #{year}\nsu mo tu th fr sa\n"    (1..length).each |day|    output << day.to_s   end   output  end end 

terminal status:

failure: testmonth#test_to_s_on_jan_2017 [test/test_month.rb:39] minitest::assertion: --- expected  +++ actual  @@ -1,9 +1,3 @@         -"january 2017  +"january 2017   su mo tu 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 31 - -" +12345678910111213141516171819202122232425262728293031" 

the string class in ruby has center method:

weekdays = "su mo tu th fr sa" month    = "#{month_names} #{year}"  output   = [   month.center(weekdays.size),    weekdays ].join("\n")  puts output #      april 2015      # su mo tu th fr sa 

the following not answer question. complete rewrite of code, because 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 |out|       out << header       out << weekdays        grouped_days.each |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 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 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