Ruby 中的 Array push()、pop() 和 clear() 函数


说到数组,Ruby 中使用最广泛的函数是 push()、pop()clear() 函数。当我们分别想要输入、取出和清除数组数据时,就会使用这些函数。在本文中,我们将逐个了解所有这些函数。

push() 函数

Ruby 中的 push 函数用于在数组的末尾追加元素。该函数可以接受单个或多个对象作为参数。

可以将以下代码作为 push() 函数的参考。

示例 1

# push() function example in Ruby

# few arrays
first_arr = ["Letters", "a", "b"]
second_arr = ["Words", "tuts", "Tuts"]
third_arr = ["Cities", "Noida", "Bangalore"]

# push() function
res_a = first_arr.push("c","d")
res_b = second_arr.push("Tut", "TutorialsPoint")
res_c = third_arr.push("Delhi", "Bangkok")

# printing result of push function
puts "#{res_a}"
puts "#{res_b}"
puts "#{res_c}"

输出

["Letters", "a", "b", "c", "d"]
["Words", "tuts", "Tuts", "Tut", "TutorialsPoint"]
["Cities", "Noida", "Bangalore", "Delhi", "Bangkok"]

pop() 函数

当我们要从数组中移除元素时,就会使用 pop 函数。它采用一个整数作为参数,该整数表示我们要从数组中删除多少个元素。

可以将以下示例作为参考。

示例 2

# pop() function example in Ruby

# few arrays
first_arr = ["Letters", "a", "b"]
second_arr = ["Words", "tuts", "Tuts","Tut", "TutorialsPoint"]

# pop() function
res_a = first_arr.pop
res_b = second_arr.pop(1)
res_c = second_arr.pop(2)

# printing result of pop function
puts "#{res_a}"
puts "#{res_b}"
puts "#{res_c}"

输出

b
["TutorialsPoint"]
["Tuts", "Tut"]

clear() 函数

clear 函数用于移除给定数组的所有元素,并返回不包含任何元素的数组。

示例 3

可以参考以下代码

# clear() function example in Ruby

# few arrays
first_arr = ["Letters", "a", "b", "c", "d"]
second_arr = ["Words", "tuts", "Tuts", "Tut", "TutorialsPoint"]
third_arr = ["Cities", "Noida", "Bangalore", "Delhi", "Bangkok"]

# clear() function
res_a = first_arr.clear
res_b = second_arr.clear
res_c = third_arr.clear
# printing result of clear function

puts "#{res_a}"
puts "#{res_b}"
puts "#{res_c}"

输出

[]
[]
[]

更新时间:2022 年 1 月 25 日

950 次浏览

开启您的职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.