23

On Ruby. I have array of array c = [["a"], ["b"]]

How convert it to c = a + b

c = ["a", "b"]

for any array. Maybe it is possible not using other variables. All array inside not flatten.

d = [ [["a"], ["b"]], [["c"], ["d"]], [["e"], ["f"]] ] 

I need [ [["a"], ["b"], ["c"], ["d"], ["e"], ["f"]] ]

6
  • 2
    Are you talking about Array#flatten right now? Commented Nov 23, 2017 at 10:42
  • flatten is not good for array of array . more deeper [[["a"], ["b"]]] i need flatter but only one step Commented Nov 23, 2017 at 10:45
  • I just edited the post to make the question clearer, I think you edited it too, you might need to do so again. Commented Nov 23, 2017 at 10:48
  • yes, notice in the docs it says "recursively". Commented Nov 23, 2017 at 10:49
  • 1
    On the first example, the input array is 2 levels deep and the output is a flat array (1 level deep). On the second example both the input and the output arrays are 3 levels deep. What's the rule? Commented Nov 23, 2017 at 10:57

3 Answers 3

35

Array#flatten also accepts a parameter.

The optional level argument determines the level of recursion to flatten.

c = [[["a"]], [["b"]]]

c.flatten
# => ["a", "b"]

c.flatten(1)
# => [["a"], ["b"]]
Sign up to request clarification or add additional context in comments.

2 Comments

How can this be used to produce the outcome describe in the question (for both examples provided)?
@axiac flatten will produce outcome from the OP's 1st eg. The second example is a typo (input & output is same). What OP is looking for is 1 level flatten, which he has mentioned in the comments.
5

Use flatten

Returns a new array that is a one-dimensional flattening of this array (recursively). That is, for every element that is an array, extract its elements into the new array. If the optional level argument determines the level of recursion to flatten.

irb(main):001:0> a =  [["a"], ["b"]]
=> [["a"], ["b"]]
irb(main):002:0> a.flatten
=> ["a", "b"]

You can control level of recursion flatten(n):

irb(main):001:0> c = [[["a"]], [["b"]]]
=> [[["a"]], [["b"]]]
irb(main):002:0> c.flatten 1
=> [["a"], ["b"]]
irb(main):003:0> 

Comments

0

Ruby:

c = [["a"], ["b"]]

Convert Array of array to Array

c.flatten

To get the sum of array of array

c.flatten.sum

3 Comments

no. d = [ [["a"], ["b"]], [["c"], ["d"]], [["e"], ["f"]] ] => ["a", "b", "c", "d", "e", "f"] I need [ [["a"], ["b"], ["c"], ["d"], ["e"], ["f"]] ]
this delete deeper structure, this is not answer
This will do it [d.flatten.collect { |x| [x] }]

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.