生まれた年と生まれた月から学年を計算・表示するコードです。
イレギュラーはあるので人によって違うこともあると思いますが、多くの人はこれに当てはまるはずです。
学年は、4月を区切りとして計算しています。
birth_year
, birth_month
には生まれた年月を、 judge_year
, judge_month
には計算するときの年月を渡します。
引数の例
- 2018年1月生まれで 2021年4月での学年を計算する場合
-
birth_year
: 2018 -
birth_month
: 1 -
judge_year
: 2021 -
judge_month
: 4
-
コード
def grade(birth_year, birth_month, judge_year, judge_month)
judge_year -= 1 if judge_month < 4
birth_year -= 1 if birth_month < 4
year = judge_year - birth_year
return "未就学" if year <= 3
return case year
when 4 then
"年少"
when 5 then
"年中"
when 6 then
"年長"
when 7 then
"小学1年"
when 8 then
"小学2年"
when 9 then
"小学3年"
when 10 then
"小学4年"
when 11 then
"小学5年"
when 12 then
"小学6年"
when 13 then
"中学1年"
when 14 then
"中学2年"
when 15 then
"中学3年"
when 16 then
"高校1年"
when 17 then
"高校2年"
when 18 then
"高校3年"
else
"卒業"
end
end
計算の流れ
4月からの1年間を年度として考えます。 年度の始まり(4月1日)においての年齢から学年が決まります。
早生まれ(1-3月生まれ)の人は birth_year
がひとつ前になりますから、 birth_year
から1を引きます。
計算年月が1-3月の場合は、 judge_year
で指定された数値より1つ前の年度の計算になりますから、 judge_year
から1を引きます。
年度の差が就学前に年少なら3年、小1進級前なら6年あります。つまり年少の場合は年度の差が4年、小1の場合は7年です。
この数値に合わせて文字列を返します。
その他
同じことをやろうとしている人は他にもいました