LoginSignup
2
1

More than 5 years have passed since last update.

rubyのおけるDateTime#===の挙動について

Last updated at Posted at 2018-03-01
require 'date'

DateTime.new(2018, 3, 1, 12, 30, 15) == DateTime.new(2018, 3, 1, 20, 30, 15)
=> false

DateTime.new(2018, 3, 1, 12, 30, 15) === DateTime.new(2018, 3, 1, 20, 30, 15)
=> true

DateTime.new(2018, 3, 1, 12, 30, 15) === DateTime.new(2018, 3, 2, 12, 30, 15)
=> false

このような挙動をする原因について解説します。
まず、DateTimeクラスのリファレンスをみてみましょう。
このクラスには===の実装はありません。
親クラスであるDateクラスには===の実装があり"同じ日なら真を返します。"と書いてあります。
ということはDateTime===Date===を実行しており日時ではなく日の比較しかしていないことがわかります。
よって日付は同じで時間だけがずれている場合はtrueを返し、日付が変わるとfalseを返すという挙動になります。

ちなみに、ここのコードにぶち当たったのが原因で調べました。

追記

rubyのソースコードにも書いてありました。

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