LoginSignup
1
0

More than 3 years have passed since last update.

【Ruby】生年月日から年齢を計算するメソッド

Last updated at Posted at 2021-04-09

生年月日から年齢を計算するメソッドを作成

まず、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歳ということがわかる。

以上、ありがとうございました。:raised_hands:

1
0
0

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
1
0