LoginSignup
0
0

More than 1 year has passed since last update.

[Ruby] shiftメソッド

Posted at

はじめに

shiftメソッドの紹介です。
プログラミング問題でsortメソッドと組み合わせると便利でした。

Array#shift

配列に対して使用できます。
配列の先頭の要素を取り出してそれを返してくれます。そしてその配列から取り出した要素は削除されています。

どういうことかというと下記の例を見てください。

array = [1, 2, 3, 4, 5]
array.shift
=> 1

このように先頭の数値を取り出してくれます。
配列の中を見て見ましょう。

p array
=> [2, 3, 4, 5]

配列の中の先頭にあった1が消えています。

また引数を渡すこともできます。渡した数字の数だけ先頭から取り出して削除してくれます。

array = [1, 2, 3, 4, 5]
array.shift(3)
=> [1, 2, 3]

p array
=> [4, 5]

ちなみに空の配列に対して使う時、引数を渡すのと、渡さない場合は結果が違うらしいです。

array = []

p array.shift
=> nil

p array.shift(1)
=> []

参考: https://docs.ruby-lang.org/ja/latest/method/Array/i/shift.html

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