79425845

Date: 2025-02-09 23:31:03
Score: 1.5
Natty:
Report link

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?

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (0.5):
Posted by: Jared