简体   繁体   中英

Remove brackets which exists in array

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...

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM