Ruby 中的陣列 shift 函式


有時我們需要提取陣列資料的一部分,並在提取的資料上進行一些操作。在 Ruby 中,我們可以藉助 shift() 函式執行此類操作。

shift() 函式接受一個引數,該引數是一個索引,用於從此索引中刪除第一個元素並返回其之前的所有元素。如果 index 無效,那麼它將返回 nil

語法

shift() 函式的語法如下所示 −

res = Array.shift(x)

在此,引數 "x" 表示開始索引。

示例 1

既然我們對陣列上的 shift() 函式有了一些瞭解,讓我們來看看如何在 Ruby 程式中使用它。考慮以下所示程式碼。

# declaring the arrays
first_arr = [18, 22, 34, nil, 7, 6]
second_arr = [1, 4, 3, 1, 88, 9]
third_arr = [18, 23, 50, 6]

# shift method example
puts "shift() method result : #{first_arr.shift(1)}
" puts "shift() method result : #{second_arr.shift(2)}
" puts "shift() method result : #{third_arr.shift()}
"

輸出

它將生成以下輸出 −

shift() method result : [18]
shift() method result : [1, 4]
shift() method result : 18

示例 2

我們再來看一個如何使用 shift() 函式的示例。

# declaring the arrays
first_arr = ["abc", "nil", "dog"]
second_arr = ["cat", nil]
third_arr = ["cow", nil, "dog", "snake"]

# shift method example
puts "shift() method result : #{first_arr.shift(1)}

" puts "shift() method result : #{second_arr.shift(2)}

" puts "shift() method result : #{third_arr.shift()}

"

輸出

它將生成以下輸出 −

shift() method result : ["abc"]
shift() method result : ["cat", nil]
shift() method result : cow

更新於: 12-4 月-2022

580 瀏覽量

讓你的 職業生涯爆發

透過完成課程獲得認證

開始
廣告
© . All rights reserved.