array ruby taking 3 last value
Ruby: Extracting the Last Three Values from an Array
# Given array
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Extracting the last three values
result = arr.last(3)
- Initialize the Array:
- Initialize the array with some values.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
.Extracting the Last Three Values:
- Use the
last
method with an argument of 3 to extract the last three values from the array. result = arr.last(3)
.Explanation:
- The
last
method in Ruby returns the last element(s) from the array. - When called with an argument of 3, it returns an array containing the last three elements of the original array.
- This method is useful for extracting a specific number of elements from the end of an array.