I would like to return the first element of an array, if the array only contains one value.
Currently, I use:
vals.one? ? vals.first : vals.presence
Thus:
vals = []; vals.one? ? vals.first : vals.presence
# => nil
vals = [2]; vals.one? ? vals.first : vals.presence
# => 2
vals = [2, 'Z']; vals.one? ? vals.first : vals.presence
# => [2, "Z"]
Is there something inbuilt that does this, or does it with a better design consideration?
My use case is specific, involving presenters that know what to expect from the method (which would implement the above code). If those presenters handle all returns as an array, then in most cases (~90%) they will iterate over arrays of size 1 or 0.
valscan either be a single (non-collection) value or a sequence (collection) of values - they are differently shaped results. As far as code, I've not seen "more idiomatic" for the desired task.vals.first unless vals.first.nil?[false].one?and[nil].one?both return false.