生年月日から年齢を計算するメソッドを作成
まず、Dateクラスは組み込みクラスとはなっていない為、Dateクラスを使うにはまずプログラムファイルの中で次の一文を記述します。
require "date"
生年月日から年齢を計算する方法
(今日 - 生年月日) ÷ 10000 なので、
例)2000年4月9日生まれの人
(20210410 - 20000409) ÷ 10000
= 21.0001 → 21歳
例)2000年4月11日生まれの人
(20210410 - 20000411) ÷ 10000
= 20.9999 → 20歳
といった感じになる。
いざ実装
def get_age(birthday)
today = Date.today.strftime("%Y%m%d").to_i
birthday = birthday.strftime("%Y%m%d").to_i
return (today - birthday) / 10000
end
get_age(2010-12-25)
Date.today で、 2020-04-10 といった感じで出力された値を、 strftime("%Y%m%d") で、20200410の形に変える。(.to_i で数値に変える)
引数 birthday でも同じ処理をする。
(birthday が 2010-12-25 の場合、 20101225)
strftimeについては以下の内容を参考
https://www.sejuku.net/blog/44796
そして、
return (today - birthday) / 10000 で計算結果を返す。
(20200410 - 20101225) ÷ 10000 = 9.9185
なので、9 が出力され、9歳ということがわかる。
以上、ありがとうございました。