如何让每一天的日期根据每一天打印(例如:苏莫图我们...等)? [英] How can I make the days of the month be printed according to each day (ex: Su Mo Tu We...etc)?

查看:170
本文介绍了如何让每一天的日期根据每一天打印(例如:苏莫图我们...等)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大的字符串,数字1-31。

I have a big String with numbers 1-31. and how would i be able to center the name of the month?

我的代码:

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"


推荐答案

p> Ruby中的String类有一个 中心 方法:

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

这篇关于如何让每一天的日期根据每一天打印(例如:苏莫图我们...等)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆