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.