8

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.

11
  • 3
    My idiom is: don't change the data shape. This violates that rule as vals can 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. Commented Nov 21, 2013 at 0:09
  • Why not just vals.first unless vals.first.nil? Commented Nov 21, 2013 at 0:17
  • 1
    Note that [false].one? and [nil].one? both return false. Commented Nov 21, 2013 at 0:26
  • 7
    As some others have hinted, this is a very bad idea - I speak from experience. If you implement this, then every call site needs to check the return type, and then act differently when it receives a scalar vs. an array. Just let the method "naturally" return a 1-element array, if it wants, and allow the call sites to know that they will always receive an array. Commented Nov 21, 2013 at 0:37
  • 3
    Yes, that's exactly what they should do, expect an array and process all the elements in the array. If there's only one they'll only need to do it once. Commented Nov 21, 2013 at 1:39

1 Answer 1

2

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 : []
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.