简体   繁体   中英

How to convert string array into array and remove empty elements?

I have a string '["", "abc", "", "def", "", "mno", "", "", "", "", ""]' . i want to convert it into array and remove empty values from that array. my desired output is abc;def;mno .

Can someone help me to do this?

You could use JSON.parse and select method:

str = '["", "abc", "", "def", "", "mno", "", "", "", "", ""]'
arr = JSON.parse(str).select(&:present?)

Output array: ["abc", "def", "mno"]

If you want to get abc;def;mno :

joined = arr.join(';')

Output string: "abc;def;mno"

Hope this helps

You can parse your string with JSON#parse and use delete with join :

str = '["", "abc", "", "def", "", "mno", "", "", "", "", ""]'
JSON.parse(str).tap { |arr| arr.delete('') }.join(';')
# => "abc;def;mno"

Use this code:

str = YAML.load('["", "abc", "", "def", "", "mno", "", "", "", "", ""]')
str.select{|a| a if a != ""}.join(";")

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