LoginSignup
42
32

More than 5 years have passed since last update.

Rubyだと日付ループがこんなに簡単に書けるのだ!

Last updated at Posted at 2016-01-16

Ruby愛ほとばしる今日の良き日に、日付ループのテクニックを備忘する。

ある期間の日付をループして表示

2000-01-01から2000-12-31までの毎日の日付を画面に出力

require 'date'
(Date.parse('2000-01-01')..Date.parse('2000-12-31')).each do |date|
  puts date
end

ある期間の毎月5日だけをループして表示

2000-01-01から2000-12-31までの毎月5日の日付を画面に出力

require 'date'
(Date.parse('2000-01-01')..Date.parse('2000-12-31')).select{|d| d.day == 5}.each do |date|
  puts date
end

ある期間の毎週日曜だけをループして表示

2000-01-01から2000-12-31までの毎週日曜の日付を画面に出力

require 'date'
(Date.parse('2000-01-01')..Date.parse('2000-12-31')).select{|d| d.wday == 0}.each do |date|
  puts date
end
42
32
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42
32