Skip to content

Commit

Permalink
Range の「要約」をさらに詳しく
Browse files Browse the repository at this point in the history
  • Loading branch information
scivola committed Mar 2, 2020
1 parent 769c0e7 commit 55e28e0
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions refm/api/src/_builtin/Range
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ include Enumerable
範囲オブジェクトは文字どおり何らかの意味での範囲を表します。数の範囲はもちろん、
日付の範囲や、「"a" から "z" まで」といった文字列の範囲を表すこともできます。

==== 作り方

範囲オブジェクトは、[[m:Range#new]] を用いるほか、範囲演算子(`..' または `...')を
用いた [[ref:d:spec/operator#range]] で生成できます。
いずれの方法でも始端と終端を与えます。
Expand All @@ -23,21 +25,41 @@ Ruby 2.6.0 からは、終端に nil を与えることで「終端を持たな
を作ることができるようになりました。

#@samplecode 終端を持たない範囲オブジェクト
p(1..nil) # 1 以上(上限無し)を表す
p(1..) # 同上(略した書き方)
p Range.new(1, nil) # 1 以上(上限無し)を表す
p(1..nil) # 同上
p(1..) # 同上(略した書き方)
#@end

#@since 2.7.0
また、Ruby 2.7.0 では始端に nil を与えることで「始端を持たない範囲オブジェクト」
を作ることもできるようになりました(どちらも持たないものも作れます)。
を作ることもできるようになりました。

#@samplecode 始端を持たない範囲オブジェクト
p(nil..5) # 5 以下(下限無し)を表す
p(..5) # 同上(略した書き方)
p Range.new(nil, 5) # 5 以下(下限無し)を表す
p(nil..5) # 同上
p(..5) # 同上(略した書き方)
#@end

始端も終端も持たない範囲オブジェクトは「全範囲」を表します。

#@samplecode 始端も終端も持たない範囲オブジェクト
# 以下はすべて同じ範囲
p Range.new(nil, nil) # => nil..nil
p(nil..nil) # => nil..nil
p(..nil) # => nil..nil
p(nil..) # => nil..nil
#@end

範囲式で両端を略した書き方はできません。

p(..) # => SyntaxError
p(...) # Ruby 2.7 で導入されたメソッド引数の forward として解釈されてしまう

#@end
#@end

==== 機能

範囲オブジェクトは範囲を表しているので、基本的な機能として「ある値がその範囲に
含まれるか否かを判定する」ということがあります。

Expand Down

0 comments on commit 55e28e0

Please sign in to comment.