0

I'm trying to extract all the elements from an array such as this: [[42, 43, 46], [23,64], [2, [2,3]]]. I figured a recursive method approach would work, but recursion is a relatively new concept to me in Ruby. Is recursion the best solution or is there a better method? I was able to extract the first deepest item within the array with this method:

def list_items(array)
  return array if array.is_a? Integer
  array = array.shift
  list_items(array)
end

set = [[42,43,46],[23,64],[2,[2,3]]]
result = list_items(set)
p result
2
  • Is your expected output [2,3] ? Commented Jan 16, 2015 at 17:26
  • 1
    I want to create a 1 dimensional array of all the items. result = [42,43,46,23,64,2,2,3] Commented Jan 16, 2015 at 17:33

1 Answer 1

1

Use #flatten method.

Returns a new array that is a one-dimensional flattening of self (recursively).

set = [[42,43,46],[23,64],[2,[2,3]]]
set.flatten # => [42, 43, 46, 23, 64, 2, 2, 3]
Sign up to request clarification or add additional context in comments.

Comments

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.