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

后端 未结 11 1666
渐次进展
渐次进展 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:30

    or a.delete_at 0

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

    Use shift method

    array.shift(n) => Remove first n elements from array 
    array.shift(1) => Remove first element
    

    https://ruby-doc.org/core-2.2.0/Array.html#method-i-shift

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

    Use the shift method on array

    >> x = [4,5,6]
    => [4, 5, 6]                                                            
    >> x.shift 
    => 4
    >> x                                                                    
    => [5, 6] 
    

    If you want to remove n starting elements you can use x.shift(n)

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

    You can use:

    arr - [arr[0]]
    

    or

    arr - [arr.shift]
    

    or simply

    arr.shift(1)
    
    0 讨论(0)
  • 2020-12-12 12:38
    [0, 132, 432, 342, 234][1..-1]
    => [132, 432, 342, 234]
    

    So unlike shift or slice this returns the modified array (useful for one liners).

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