1
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 3 years have passed since last update.

【Ruby】配列の先頭に要素を挿入するunshiftメソッドの使い方

Posted at

#プログラミング勉強日記
2021年4月4日

#unshiftメソッドとは
 配列の先頭に引数で指定した要素を挿入するメソッド。(pushメソッドは配列の最後に要素を追加する。)
 引数を指定しなければ何も起こらない。

使い方
配列.unshift(引数, ...)

#サンプルプログラム

# 配列を定義
num = [1, 2, 3, 4, 5]

puts "挿入前:#{num}"

# 配列の先頭に要素を挿入する
num.unshift(0)

puts "挿入後#{num}"
実行結果
挿入前:[1, 2, 3, 4, 5]
挿入後:[0, 1, 2, 3, 4, 5]

#参考文献
instance method Array#prepend

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