红宝石 |数组类 last()函数
last()是一个 Array 类方法,它返回数组的最后一个元素或数组中的最后 'n' 个元素。第一种形式返回 nil,如果数组为空。
Syntax: Array.last()
Parameter: Array
n – no. of elements
Return: last element of the array or the last ‘n’ elements from the array
示例 #1:
# Ruby code for last() method
# declaring array
a = [18, 22, 33, nil, 5, 6]
# declaring array
b = [1, 4, 1, 1, 88, 9]
# declaring array
c = [18, 22, nil, nil, 50, 6]
# last
puts "last : #{a.last(5)}\n\n"
# last
puts "last : #{b.last(4)}\n\n"
# last
puts "last : #{c.last()}\n\n"
输出 :
last : [22, 33, nil, 5, 6]
last : [1, 1, 88, 9]
last : 6
示例 #2:
# Ruby code for last() method
# declaring array
a = ["abc", "nil", "dog"]
# declaring array
b = ["cow", nil, "dog"]
# declaring array
c = ["cat", nil, nil]
# last
puts "last : #{a.last(5)}\n\n"
# last
puts "last : #{b.last(4)}\n\n"
# last
puts "last : #{c.last()}\n\n"
输出 :
last : ["abc", "nil", "dog"]
last : ["cow", nil, "dog"]
last :