红宝石 |弹出()函数
Ruby 中的 pop()函数用于弹出或删除给定数组的最后一个元素并返回删除的元素。
Syntax: pop(Elements)
Parameters:
Elements : This is the number of elements which are to be removed from the end of the given array. If this parameter is not used then it removes and returns the single last element of the given array.
Returns: the removed elements.
示例 1:
# Initializing some arrays of elements
Array = [1, 2, 3, 4, 5, 6, 7]
# Calling pop() function
A = Array.pop
B = Array.pop(2)
C = Array.pop(3)
D = Array
# Printing the removed elements
puts "#{A}"
puts "#{B}"
puts "#{C}"
# Printing the remaining array
puts "#{D}"
输出:
7
[5, 6]
[2, 3, 4]
[1]
示例 2:
# Initializing some arrays of elements
Array = ["a", "b", "c", "d", "e", "f", "g"]
# Calling pop() function
A = Array.pop
B = Array.pop(1)
C = Array.pop(2)
D = Array.pop(3)
E = Array
# Printing the removed elements
puts "#{A}"
puts "#{B}"
puts "#{C}"
puts "#{D}"
# Printing the remaining array
puts "#{E}"
输出:
g
["f"]
["d", "e"]
["a", "b", "c"]
[]
参考: https://devdocs.io/ruby~2.5/array#method-i-pop