Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 698
New Alexandria Avatar asked Nov 21 '13 00:11

New Alexandria


People also ask

How do you find if an element exists in an array in Ruby?

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.

Does each return an array Ruby?

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

How do you remove the first element from a list in Ruby?

You can use Array. delete_at(0) method which will delete first element.


1 Answers

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 : []
like image 56
SteveTurczyn Avatar answered Sep 20 '22 06:09

SteveTurczyn