5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

shift, unshift, pop, pushまとめ

Posted at

##shiftメソッド

shift.rb
a = [0, 1, 2, 3, 4,]
a.shift
=> 0 #先頭の要素を返すため今回の場合はa.shift.classを実行するとIntegerが帰ってくる。
a #shiftは破壊的メソッドなので、ローカル変数aの値は[1, 2, 3, 4,]になる
=> [1, 2, 3, 4,]
a.shift(2)
=> [1, 2] #a.shift(2).classはArrayを返す。
a.size
=> 2
a.shift(3) #配列の要素数以上を指定すると、その時の要素全てを配列として返す
=> [3, 4]

b = [1, 2]
b.shift(0)
=> [] #引数を指定しないと空配列を返す。
b.shift(1) #引数に1を指定すると配列の最初の要素を配列に入れて返す。
=> [1]

#空配列に対する挙動
a = []
a.shift
=> nil #引数を指定しないとnilを返す
a.shift(2)
=> [] #引数を指定すると空配列を返す
a.shift(0)
=> []

参考にしたページ

popメソッド

pop.rb
a = [0, 1, 2, 3, 4,]
a.pop
=> 4
a 
=> [0, 1, 2, 3,]
a.pop(2)
=> [2, 3]
a.size
=> 2
a.pop(3) 
=> [0, 1]

b = [1, 2]
b.pop(0)
=> [] 
b.pop(1) 
=> [2]

#空配列に対する挙動
a = []
a.pop
=> nil
a.pop(2)
=> [] 
a.pop(0)
=> []

参考にしたページ

pushメソッド

push.rb
a = [0, 1, 2]
a.push(3)
a
=> [0, 1, 2, 3,]
a.push([4, 5])
=> [0, 1, 2, 3, [4, 5]]
a.pus('hoge') #String型のオブズエクトも大丈夫
=> [0, 1, 2, 3, [4, 5], 'hoge']

参考にしたページ

unshiftメソッド

unshift.rb
a = [3, 4, 5]
a.unshift(2)
a
=> [2, 3, 4, 5]
a.unshift([0, 1])
=> [[0, 1], 2, 3, 4, 5]
a.unshift('hoge')
=> ["hoge", [0, 1], 2, 3, 4, 5]

参考にしたページ

おまけ
pushとunshiftは自分自身を代入することができる。

ruby,rb
a = [0, 1, 2]
a.push(a)
=> [0, 1, 2, [...]]
a.unshift('hoge')
=> ["hoge", 0, 1, 2, [...]]
a.pop #[...]を取り出す時のaを返す。
=> ["hoge", 0, 1, 2,]
5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?