简体   繁体   English

如何将字符串数组转换为数组并删除空元素?

[英]How to convert string array into array and remove empty elements?

I have a string '["", "abc", "", "def", "", "mno", "", "", "", "", ""]' .我有一个字符串'["", "abc", "", "def", "", "mno", "", "", "", "", ""]' i want to convert it into array and remove empty values from that array.我想将它转换成数组并从该数组中删除空值。 my desired output is abc;def;mno .我想要的输出是abc;def;mno

Can someone help me to do this?有人可以帮我做这个吗?

You could use JSON.parse and select method: 您可以使用JSON.parseselect方法:

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

Output array: ["abc", "def", "mno"] 输出数组: ["abc", "def", "mno"]

If you want to get abc;def;mno : 如果您想获得abc;def;mno

joined = arr.join(';')

Output string: "abc;def;mno" 输出字符串: "abc;def;mno"

Hope this helps 希望这可以帮助

You can parse your string with JSON#parse and use delete with join :您可以使用JSON#parse解析您的字符串,并使用deletejoin

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(";")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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