Rob
Rob

Reputation: 1855

`Array#join` on nested arrays only

I have an array of arrays. The second element of each subarray is further an array:

arr = [
  ["val1", ["The cat", "3"]],
  ["val2", ["Big", "Another", "6"]],
  ["val3", ["343"]]
]

I would like to convert the array so that the arrays at the third nested level are each joined into one string separated by a space and comma like this:

[["val1", "The cat, 3"], ["val2", "Big, Another, 6"], ["val3", "343"]]

How do I call join on just the nested arrays?

Upvotes: 1

Views: 1821

Answers (4)

Damon
Damon

Reputation: 4336

Do the following to your array

array.map {|el| el.flatten}

Edit : Per your update, you can accomplish joining the deeply nested arrays as follows:

array.map {|x| x.map {|y| y.is_a?(Array) ? y.join(', ') : y}}

Upvotes: 2

sawa
sawa

Reputation: 168101

arr.map{|e, a| [e, a.join(", ")]}
# => [["val1", "The cat, 3"], ["val2", "Big, Another, 6"], ["val3", "343"]]

Upvotes: 2

glenn mcdonald
glenn mcdonald

Reputation: 15488

map and flatten are your friends!

a.map(&:flatten)

Upvotes: 1

Babar Al-Amin
Babar Al-Amin

Reputation: 3984

You can do it by concatenating it inside a loop.

arr = [["val1", ["The cat", "3"]], ["val2", ["Big", "Another", "6"]], ["val3", ["343"]]

arr.map{|a| [a.first] + a.last}
#=> [["val1", "The cat", "3"], ["val2", "Big", "Another", "6"], ["val3", "343"]]

Or simply flatten in inner arrays:

arr.map(&:flatten)

Upvotes: 0

Related Questions