Is there a ruby idiom for returning the first array element, if only one exists?

arrays, ruby, ruby-on-rails

Solution

You seem to want to handle the case of val array being undefined so...

val.size > 1 ? val : val[0] if defined?(val)

But as has been pointed out it would be better to deliver a consistent argument (always arrays) so the following will deliver the val array or an empty array if undefined

defined?(val) ? val : []

Problem

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`.

Original source

Related problems