Reputation: 75
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
Upvotes: 0
Views: 51
Reputation: 118261
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]
Upvotes: 1