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
.
This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.
#Each and #Map They will both iterate (move through) an array, but the main difference is that #each will always return the original array, and #map will return a new array. create a new object with each: #each_with_object is a useful method that lets you add to a given object during each iteration.
You can use Array. delete_at(0) method which will delete first element.
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 : []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With