Ruby 的 Array # shift 做什么?

我很难理解 Array 类的 shift 和 unshift 方法在 Ruby 中的作用。谁能告诉我他们在做什么?

56895 次浏览

It grabs the first element, removes it from the array, and returns the removed element. It's basically a way to treat an array like a stack: shift is pop, unshift is push.

It returns the first element of the array, and removes it from the array, shifting the elements back one place.

So shifting [1,2,3,4,5]

returns 1, and sets the array to be [2,3,4,5].

More here.

shift and unshift0 acts in similar way as unshift1 and unshift2: they are meant to use arrays as stacks to which you can append and remove elements (usually one per time). The difference is just that shift and unshift add/remove elements at the beginning of an Array, actually unshift3ing all other elements, while pop and push add/remove elements at the end of the Array, so preserving other elements' indices.

Examples:

                      # Spacing for clarity:
a = [2, 4, 8]    # a =>       [2, 4, 8]
a.push(16, 32)   # a =>       [2, 4, 8, 16, 32]
a.unshift(0, 1)  # a => [0, 1, 2, 4, 8, 16, 32]
a.shift          # a =>    [1, 2, 4, 8, 16, 32]
a.pop            # a =>    [1, 2, 4, 8, 16]

Looking at the Ruby Documentation

Array.shift removes the first element from the array and returns it

a = [1,2,3]
puts a.shift
=> 1
puts a
=> [2, 3]

Unshift prepends the provided value to the front of the array, moving all other elements up one

a=%w[b c d]
=> ["b", "c", "d"]
a.unshift("a")
=> ["a", "b", "c", "d"]

If you can think of the array as being like a queue of values to be processed, then you can take the next (front) value and "shift" the other valuess over to occupy the space made available. unshift puts values back in - maybe you're not ready to process some of them, or will let some later code handle them.