28
11

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 | 配列で最初の要素だけを削除する ( 2行目以降を全て得る )

Last updated at Posted at 2016-01-26

解決

drop すれば良い。

['A','B','C','D','E'].drop(1)

# => ["B", "C", "D", "E"]

問題

shift の返り値

配列を shift すると、取り出した要素が返り値になる。
残った要素ではない。

['A','B','C','D','E'].shift

=> "A"

shift!

shift はそもそも破壊的。だから shift! なんてない。

['A','B','C','D','E'].shift!
# => NoMethodError: undefined method `shift!' for ["A", "B", "C", "D", "E"]:Array

一時変数

求める値は得られるが。3行も書かなければいけない。

alphabets = ['A','B','C','D','E'] 

alphabets.shift

alphabets 

# =>  ["B", "C", "D", "E"]

過去

今までは配列に対して [1..-1] を問うていた。

['A','B','C','D','E'][1..-1]

# => ["B", "C", "D", "E"]

1 は配列の二番目という意味。 ( 2 ではない )
-1 は配列の最後という意味。

環境

  • Ruby 2.2.4

謝辞

  • drop を教えてくれた @pinzolo さん
  • shift がそもそも破壊的だと指摘してくれた @scivola さん

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

28
11
3

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
28
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?