0
0

範囲オブジェクト

Posted at

範囲オブジェクトとは

範囲オブジェクトとは、「〇から〇まで」のような、値の範囲を表すオブジェクトのこと。

作成方法

1から10までの場合以下のように表す。

a = 1..10
a.include?(10)
=> true

include?メソッドで確認すると、10まで範囲に含まれていることがわかる。
10を含めたくない場合は、「.」の数を3つにすることで範囲を10未満にすることができる。

a = 1...10
a.include?(10)
=> false

使用例

〇以上〇以下や、〇以上〇未満を判定したい時は、不等号を使用するよりも、範囲オブジェクトを使用した方がシンプルに記述することができる。

def number_of_people(num) 
  1 <= num && num < 10
end

def number_of_people(num)
  (1...10).include?(num)
end
0
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
0
0