Remove brackets which exists in array

Viewed 65

I do have an array which looks like:

["[0, 1]", "0", "1"]

The question is how to remove brackets inside the array, so the result which I wish to get would be:

["0", "1", "0", "1"]

Currently, I'm out of idea...

3 Answers

Depending on the specific structure of the array elements, you might be able to scan the elements for things that look like numbers and then use flat_map to unroll the arrays you get from scan:

['[0, 1]', '0', '1'].flat_map { |e| e.scan(/\d+/) }
# ["0", "1", "0", "1"] 

This is what I came up with:

["[0, 1]", "0", "1"].to_s.split(/\W/).reject(&:blank?)

If the array elements might be nested, then I would go straight to YAML or JSON parsers:

require 'json'
['[0, [1, 0], 1]', '0', '1'].flat_map { |s| JSON.parse(s) }

# => [0, [1, 0], 1, 0, 1]
Related