Provided answers for empty or size of 1 arrays can give you unexpected results. It might be worth in some situations to be sure that if array is empty, first and last values don't exist, or in case of 1 element last or(!) first element is empty. Use delete_at
, with caution:
def first_last(arr)
arr = arr.dup # avoid changing the original array
[arr.delete_at(0), arr.delete_at(-1)].compact # remove compact if `nil` is ok for you
end
a = []; first_last(a) => []
b = ["a"]; first_last(b) => ["a"]
c = ["a", "b", "c"]; first_last(c) => ["a", "c"]
In this situation arrays of 1 element are nice thought experiment - do they have only first or only last element?