Last active
October 28, 2022 09:27
-
-
Save gouf/92cd7f29080c453d27c92e4b0181d091 to your computer and use it in GitHub Desktop.
年月 (from, to) のデータから、のべ年数を計算する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20143 20149 | |
20162 20175 | |
20162 20164 | |
20165 20166 | |
20169 201611 | |
20172 20175 | |
20181 20192 | |
20194 20195 | |
20203 20208 | |
202011 20222 | |
20227 202211 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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