Skip to content

Instantly share code, notes, and snippets.

@gouf
Last active October 28, 2022 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gouf/92cd7f29080c453d27c92e4b0181d091 to your computer and use it in GitHub Desktop.
Save gouf/92cd7f29080c453d27c92e4b0181d091 to your computer and use it in GitHub Desktop.
年月 (from, to) のデータから、のべ年数を計算する
20143 20149
20162 20175
20162 20164
20165 20166
20169 201611
20172 20175
20181 20192
20194 20195
20203 20208
202011 20222
20227 202211
require 'active_support'
require 'active_support/core_ext'
require 'date'
date_matcher = /^(^\d{,4})(\d+?)$/ # 年・月で区切る
data =
File.read(File.join(__dir__, 'data.txt'))
.lines
.map(&:chomp)
.map { |x| x.split.map { |y| y.match(date_matcher).captures.map(&:to_i) } }
days_array =
data.map do |from, to|
from_date = Date.new(*from)
to_date = Date.new(*to)
(to_date - from_date).to_i
end
pp days_array.sum.days.in_years.to_i # => 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment