97
93

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.

Ruby で楽に範囲のチェックをする

Posted at

範囲のチェックをする時に、

hoge >= min and hoge <= max

と書くのはめんどくさい。

Comparable module をインクルードしているクラスでは between? メソッドを使って楽にチェックができる。

between?(min, max)

Fixnum でも使えるし:

1.9.3p194 :228 > 10.between?(1, 10)
 => true
1.9.3p194 :229 > 11.between?(1, 10)
 => false

DateTime でも使える:

1.9.3p194 :230 > DateTime.parse('2012-10-01').between?(DateTime.parse('2012-01-01'), DateTime.parse('2012-12-31'))
 => true
1.9.3p194 :231 > DateTime.parse('2013-01-01').between?(DateTime.parse('2012-01-01'), DateTime.parse('2012-12-31'))
 => false
97
93
4

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
97
93

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?