0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rangeオブジェクト ー exclusiveとinclusive

Posted at

一つ前に書いたtimesメソットについての記事の中で、Range(範囲オブジェクト)に触れていたので、備忘録的にここにまとめておこうと思う。皆様、どうかお付き合いください。🙇

範囲オブジェクトとは

  • 連続した値の集合を表すRuby標準クラスのこと

排他的範囲(...)とは

  • 開始値を含み、終了値を含まない範囲を表すこと
  • 数値だけでなく、文字やオブジェクトにも適用可能なこと
  • 記法: (a...b)  👈 a ≤ x < b

包括的範囲(..)とは

  • 開始値を含み、終了値も含む範囲を表すこと
  • 数値だけでなく、文字やオブジェクトにも適用可能なこと
  • 記法: (a..b)  👈 a ≤ x ≤ b

具体例①:配列のインデックス指定

array = %w[a b c d e f g]

p array[0...5]  # => ["a", "b", "c", "d", "e"]
p array[0..5]   # => ["a", "b", "c", "d", "e", "f"]

具体例②:eachメソッドによる繰り返し

  • 排他的範囲
(1...5).each do |i|
  puts i
end
# 実行結果:
# 1
# 2
# 3
# 4
  • 包括的範囲
(1..5).each do |i|
  puts i
end
# 実行結果:
# 1
# 2
# 3
# 4
# 5

俺の覚え方

  • 3アウトチェンジ=終端排他

まとめてみて

  • times メソッドは包括的範囲のRangeを使って書くようにしたい。
5.times do |i|

これよりも

(0..4).each do |i|

こっちの方が見やすいし、times メソッドは「0スタートのn-1終わり」とか覚えてられなそう・・・

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?