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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
CodeLover
  • 1,054
  • 6
  • 24
  • 40
  • 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. – the Tin Man Feb 22 '14 at 04:39
  • @Arup's answer is great, but it is also worth noting that you can rapleace `is_a?` with `===`. *cf.* http://stackoverflow.com/questions/3422223/vs-in-ruby – nodakai Feb 22 '14 at 04:51

1 Answers1

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 :-)

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317