1

I have an array structure that looks like:

a=[
  [['a','A'],['b','B'],['c','C']],
  [['d','D'],['e','E'],['f','F']]
]

How to merge inner two arrays so the new structure will be Array of arrays

[
 ['a','A'],['b','B'],['c','C'],['d','D'],['e','E'],['f','F']
]

Tried

a.inject([]){|k,v| v | k} # but order gets changed
=> [["d", "D"], ["e", "E"], ["f", "F"], ["a", "A"], ["b", "B"], ["c", "C"]]

How can i get desired result without loosing the order.

Tips, comments, suggestions, please?

Thnx.

Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113
hitesh israni
  • 1,742
  • 4
  • 25
  • 48

2 Answers2

5

array.flatten takes a parameter:

a.flatten(1) #[["a", "A"], ["b", "B"], ["c", "C"], ["d", "D"], ["e", "E"], ["f", "F"]]
steenslag
  • 79,051
  • 16
  • 138
  • 171
  • wow! thats nice solution. i have been trying flatten without parameter, which was giving ["a", "A", "b", "B", "c", "C", "d", "D", "e", "E", "f", "F"] can you please explain the need for parameter here. thnx – hitesh israni Apr 19 '12 at 08:57
  • 1
    The parameter specifies how much levels you want to flatten. The default is 'all'; in this case just 1 level is sufficient. – steenslag Apr 19 '12 at 09:00
1

Try this:

a.inject([]){|k,v| k|v}
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176