🖥

Ruby | Delete only the first element in the array (get everything afte

に公開

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オープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-04-16

Discussion