LoginSignup
1
0

More than 5 years have passed since last update.

Ruby の Array でまとめて pop / shift

Posted at

Ruby の配列操作である Array#popArray#shift は引数を渡すことが可能で、渡した引数の値の数の要素を取得することが出来ます。(0 を与えた場合は空配列が返ってきます)

list = [1, 2, 3, 4, 5]

a = list.pop(5)

p list #=> []
p a    #=> [1, 2, 3, 4, 5]
list = [1, 2, 3, 4, 5]

a = list.shift(3)

p list #=> [4, 5]
p a    #=> [1, 2, 3]

気をつけないといけないのは、空配列に対する操作を行った場合に引数を与えている場合は nil ではなく空配列を返すので、下記のようなコードを書いてしまうと大変なことになります。

list = [1, 2, 3, 4, 5]

while a = list.pop(2)
  p a
end

結果

[4, 5]
[2, 3]
[1]
[]
[]
[]
[]
[]
[]
[]
[]
.
.
.
以下無限ループ

参考サイト

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

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