1

Really simple question.

Is there a method to do the following?

["a"] => "a"
[1] => 1
[1,"a"] => [1, "a"]

i.e. if an array is a single object, return the object, otherwise return the array. Without doing something ugly like

array.length == 1 ? array[0] : array
5
  • 3
    Not to my knowledge -- but why would you want to do this? Whatever you're passing this data to should respond to either an array or a string, popping out a single value if it's alone means that your code further along has to know how to deal with both arrays and strings, rather than just relying n always having an array. Commented Mar 10, 2016 at 20:33
  • 4
    Possible duplicate of Is there a ruby idiom for returning the first array element, if only one exists? Commented Mar 10, 2016 at 20:38
  • Doing this has code smell. Commented Mar 10, 2016 at 20:42
  • To clarfiy, one of the reasons I want to do it is that I want to replicate the functionality of the .pluck method in rails 4 for rails 3. Pluck in rails 4 returns either single objects, if only one column is plucked, or an array of multiple objects, if multiple objects are plucked. Commented Mar 11, 2016 at 12:04
  • In terms of the duplicate. You probably have a point there. However, I'm not sure that the question title is easy enough to find in order to stop people being stuck. (Hence I didn't find it...) Not sure if I accept the duplicate in that case... Commented Mar 11, 2016 at 12:05

1 Answer 1

1

basically you should stick to what you wrote - it's simple and does what it should.

of course you may always monkey patch the Array definition... (unrecommended, but it does what you expect)

class Array
  def first_or_array
    length > 1 ? self : self[0]
  end
end

[1].first_or_array # 1
[1, 2].first_or_array # [1, 2]
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly this! I was going to post the same. But I'd add something. This not excludes the possibility of having something like [[1,2]] and then [[1,2]].first_of_array = [1,2], still an array, although the content is a single object (another array). This would have to be something recursive, if the goal is to reach a single object.
If you can't do any better than the OP, you should just suggest the OP to go with that way. This does need to be an answer. It could just be a comment.

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.