如何根据每一天打印一个月中的几天(例如:Su Mo Tu We ...等)?

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

我有一个包含数字 1-31 的大字符串。我怎样才能将月份的名称居中?

我的代码:

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 We Th Fr Sa\n"
   (1..length).each do |day|
   output << day.to_s
  end
  output
 end
end

终止状态:

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 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 31
-
-"
+12345678910111213141516171819202122232425262728293031"

Ruby 中的字符串 class 有一个 center 方法:

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

以下内容并未真正回答您的问题。这只是对你的代码的完全重写,因为我很无聊:

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