0

I want to create an array of arrays from another array:

a = [11,1,[23,21],14,[90,1]]
a.map { |e| e.is_a?(Array) ? e : [e] }
# => [[11], [1], [23, 21], [14], [90, 1]]

Is there an elegant way to do this?

2
  • What's wrong with how you're doing it? Looking at what you're getting in your result makes me think there's another problem underneath this that should be fixed. Receiving an array of the form that yours is hints of code smell and you're trying to work around it instead of addressing the problem of getting single elements mixed with sub-arrays. Commented Feb 22, 2014 at 4:39
  • @Arup's answer is great, but it is also worth noting that you can rapleace is_a? with ===. cf. stackoverflow.com/questions/3422223/vs-in-ruby Commented Feb 22, 2014 at 4:51

1 Answer 1

6

I would do as below :

a = [11,1,[23,21],14,[90,1]]
a.map { |e| [*e] }
# => [[11], [1], [23, 21], [14], [90, 1]]

or using Kernel#Array()

a.map { |e| Array(e) }
# => [[11], [1], [23, 21], [14], [90, 1]]

Use, which ever you think as elegant, for me both are elegant :-)

Sign up to request clarification or add additional context in comments.

4 Comments

Great ideas!.. I'll catch you in the morning.. very sleepy (3:00 am here)
Here 6-40 am :-) @Abdo
Nice, Arup. I'll have to remember those two little gems.

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.