Techioz Blog

day = Date.today.wday メソッドを使用して「日」を表示するには、Ruby コードをどのように記述しますか?

概要

私は学校からのRubyの課題をやっています。 カレンダーアプリケーションに曜日(日曜日、月曜日など)が表示されるようにする必要があります。 以下は私が受け取った質問の元のコードです。

class CalendarsController < ApplicationController
  def index
    getWeek
    @plan = Plan.new
  end

  def create
    Plan.create(plan_params)
    redirect_to action: :index
  end

  private

  def plan_params
    params.require(:calendars).permit(:date, :plan)
  end

  def getWeek
    wdays = ['(Sun)','(Mon)','(Tue)','(Wed)','(Thu)','(Fri)','(Sat)']

    @todays_date = Date.today
   
    @week_days = []

    plans = Plan.where(date: @todays_date..@todays_date + 6)

    7.times do |x|
      today_plans = []
      plans.each do |plan|
        today_plans.push(plan.plan) if plan.date == @todays_date + x
      end
      days = { :month => (@todays_date + x).month, :date => (@todays_date+x).day, :plans => today_plans}
      @week_days.push(days)
    end

  end
end

以下のようにコードを書いてみました。

@todays_date = Date.today.wday

アプリケーションに曜日(日曜日、月曜日など)が表示されることを期待していました

解決策

今日は水曜日です。日付を曜日の文字列表現に変換したい場合は、次のように Date#strftime を使用できます。

Date.today.strftime("%A")
#=> "Wednesday"
Date.today.strftime("%a")
#=> "Wed"

Date.today.strftime("(%a)")
#=> "(Wed)"