0
0

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 | Delete only the first element in the array (get everything after the second line)

0
Last updated at Posted at 2019-04-16

Solution

drop it.

 ['A','B','C','D','E'].drop(1) # => ["B", "C", "D", "E"] 

problem

shift return value

If you shift the array, the extracted element will be the return value. It is not a remaining element.

 ['A','B','C','D','E'].shift => "A" 

shift!

shift is destructive in the first place. So there is no shift!

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

Temporary variable

I can get the value I want. I have to write three lines.

 alphabets = ['A','B','C','D','E'] alphabets.shift alphabets # => ["B", "C", "D", "E"] 

past

So far, I have been asking [1..-1] for arrays.

 ['A','B','C','D','E'][1..-1] # => ["B", "C", "D", "E"] 

1 means the second of the array. (Not 2 ) -1 means the end of the array.

environment

  • Ruby 2.2.4

Acknowledgment

  • @pinzolo who taught me drop
  • @scivola who pointed out that shift is destructive in the first place

Original by

Ruby | 配列で最初の要素だけを削除する ( 2行目以降を全て得る )

About

About this translattion

チャットメンバー募集

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

Twitter

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?