18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rangeは、Timeでも使えた!

Last updated at Posted at 2013-08-12

1から6までの数値が含まれているかいないかというのを書く場合
おそらく多くの人が

(1..6).include?(3)
#=> true
(1..6).include?(9)
#=>false

というように書くと思います。

でこの範囲オブジェクトがなんと日付でも使えたという!
恥ずかしながら私、最近初めて知りました。

例えば・・・

time = (Time.now - 10.days)..(Time.now)
#=> Fri Aug 02 13:54:51 +0900 2013..Mon Aug 12 13:54:51 +0900 2013

とすると

time.end
#=> Mon Aug 12 13:54:51 +0900 2013
time.begin
#=> Fri Aug 02 13:54:51 +0900 2013

さらに・・・

time.include?(Time.now)
#=> false 
time.include?(Time.now - 3.days)
#=> true 

時間単位でもできちゃう!

hours = (1.hour)..(3.hour)
#=> 3600 seconds..10800 seconds 
hours.include?(1.hour)
#=> true 
hours.include?(4.hour)
#=> false 

おらおら日付でもできちゃうぜ!!

days = (1.days)..(5.days)
#=> 1 day..5 days 
days.include?(2.days)
#=> true 
days.include?(6.days)
#=> false 

おおおお!スゴイです!!
こんなことができるのを知らないでいたなんで!!!
無限の可能性を感じてきたぞ・・・

18
19
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
18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?