1
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?

sliceの使い方まとめ

Posted at

Rubysilverの勉強してたら出てきました。
Rubyの配列操作でよく登場するのが slice メソッド らしいです。
似た書き方に a[index, length] もありますが、どちらもほぼ同じ挙動をするそうです!

基本の書式

array.slice(index, length)

•index : 取り出し開始位置(0始まり)
•length : 取り出す要素の個数

結果は「部分配列」として返ってくる。

例1:基本的な使い方

a = [1, 2, 3, 4]
p a.slice(2, 1)  # => [3]

•index = 2 → 0始まりで「3」
•length = 1 → 1個だけ取り出す
結果は [3] となる。

例2:複数取り出す

a = [1, 2, 3, 4]
p a.slice(2, 2)  # => [3, 4]
p a.slice(0, 3)  # => [1, 2, 3]

•index = 2 → 0始まりで「3」
•length = 2 → 2個だけ取り出す
結果は [3, 4] となる。

•index = 0 → 0始まりで「1」
•length = 3 → 3個だけ取り出す
結果は [1, 2, 3] となる。

例3:範囲外を指定した場合

a = [1, 2, 3, 4]
p a.slice(10, 1)  # => nil

範囲外の場合は nil が返る のもポイント!

a[index, length] との違いは?

a = [1, 2, 3, 4]
p a[2, 1]     # => [3]
p a.slice(2,1) # => [3]

書き方が違うだけで、挙動は一緒!

1
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
1
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?