Ruby: What is the easiest way to remove the first element from an array?

后端 未结 11 1665
渐次进展
渐次进展 2020-12-12 11:54

Lets say I have an array

[0, 132, 432, 342, 234]

What is the easiest way to get rid of the first element? (0)

相关标签:
11条回答
  • 2020-12-12 12:12

    You can use Array.delete_at(0) method which will delete first element.

     x = [2,3,4,11,0]
     x.delete_at(0) unless x.empty? # [3,4,11,0]
    
    0 讨论(0)
  • 2020-12-12 12:13

    This is pretty neat:

    head, *tail = [1, 2, 3, 4, 5]
    #==> head = 1, tail = [2, 3, 4, 5]
    

    As written in the comments, there's an advantage of not mutating the original list.

    0 讨论(0)
  • 2020-12-12 12:16
    a = [0,1,2,3]
    
    a.drop(1)
    # => [1, 2, 3] 
    
    a
    # => [0,1,2,3]
    

    and additionally:

    [0,1,2,3].drop(2)
    => [2, 3]
    
    [0,1,2,3].drop(3)
    => [3] 
    
    0 讨论(0)
  • 2020-12-12 12:16

    You can use:

     a.delete(a[0])   
     a.delete_at 0
    

    Both can work

    0 讨论(0)
  • You can use:

    a.slice!(0)
    

    slice! generalizes to any index or range.

    0 讨论(0)
  • 2020-12-12 12:27

    "pop"ing the first element of an Array is called "shift" ("unshift" being the operation of adding one element in front of the array).

    0 讨论(0)
提交回复
热议问题