Ruby | Array class last() function
last() is a Array class method which returns the last element of the array or the last ‘n’ elements from the array. The first form returns nil, If the array is empty .
Syntax: Array.last()
Parameter: Array
n – no. of elementsReturn: last element of the array or the last ‘n’ elements from the array
Example #1 :
# Ruby code for last() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # lastputs "last : #{a.last(5)}\n\n" # lastputs "last : #{b.last(4)}\n\n" # lastputs "last : #{c.last()}\n\n" |
Output :
last : [22, 33, nil, 5, 6] last : [1, 1, 88, 9] last : 6
Example #2:
# Ruby code for last() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayb = ["cow", nil, "dog"] # declaring arrayc = ["cat", nil, nil] # lastputs "last : #{a.last(5)}\n\n" # lastputs "last : #{b.last(4)}\n\n" # lastputs "last : #{c.last()}\n\n" |
Output :
last : ["abc", "nil", "dog"] last : ["cow", nil, "dog"] last :



