Why does shift(1) return a number with brackets around it, but shift() does not? [closed]

StackOverflow https://stackoverflow.com/questions/19738768

  •  03-07-2022
  •  | 
  •  

質問

So for example:

def ding_dong()
    p @arr.shift(1)
    p @arr.shift
end

If I call this with:

ding_dong([0,1,2,3,4])

Why does the first puts return "[0]" and the second return "1" without the brackets?

役に立ちましたか?

解決

From the documentation on Array#shift:

shift → obj or nil

shift(n) → new_ary

Returns the first element of self and removes it (shifting all other elements down by one). Returns nil if the array is empty.

If a number n is given, returns an array of the first n elements (or less) just like array.slice!(0, n) does.

Try using shift(0) and shift(2) and see what happens.

When accepting any number, it makes most sense to return an Array, even when the result is a single element. Otherwise the caller would have to write special-case code for when n was 0 or 1 (or when there was 0 or 1 sliced elements).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top