[英]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.parse
并select
方法:
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
解析您的字符串,并使用delete
和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(";")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.