Open2

AtCoder対策 Rubyの使い方

daylightdaylight

配列操作

削除

要素の削除

doc: https://docs.ruby-lang.org/ja/latest/method/Array/i/delete.html

array = [1, 2, 3, 2, 1]
p array.delete(2)       #=> 2
p array                 #=> [1, 3, 1]

指定位置の要素削除

doc: https://docs.ruby-lang.org/ja/latest/method/Array/i/delete.html

array = [0, 1, 2, 3, 4]
array.delete_at 2
p array             #=> [0, 1, 3, 4]

条件に合うものを削除

doc: https://docs.ruby-lang.org/ja/latest/method/Array/i/delete_if.html

a = [0, 1, 2, 3, 4, 5]
a.delete_if{|x| x % 2 == 0}
p a #=> [1, 3, 5]
daylightdaylight

配列のQueue・Stack操作

Queue

FIFO。店に並んでいる時の行列のイメージ。

末尾の要素追加

doc: https://docs.ruby-lang.org/ja/latest/method/Array/i/push.html

array = [1, 2, 3]
array.push 4
array.push [5, 6]
array.push 7, 8
p array          # => [1, 2, 3, 4, [5, 6], 7, 8]

先頭の要素削除

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

a = [0, 1, 2, 3, 4]
p a.shift            #=> 0
p a                  #=> [1, 2, 3, 4]

Stack

LIFO。洗った皿を積んで、また使う時のイメージ。

末尾の要素追加

上と同様。
doc: https://docs.ruby-lang.org/ja/latest/method/Array/i/push.html

array = [1, 2, 3]
array.push 4
array.push [5, 6]
array.push 7, 8
p array          # => [1, 2, 3, 4, [5, 6], 7, 8]

末尾の要素削除

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

array = [1, [2, 3], 4]
p array.pop      # => 4
p array.pop      # => [2, 3]
p array          # => [1]

参考