-1

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?

4
  • You can simple do it in one line using JSON.parse(a).reject(&:empty?).join(';') Commented Jan 19, 2018 at 11:51
  • Just for your example string.scan(/\w+/) #=> ["abc", "def", "mno"] but not really a general solution. Commented Jan 19, 2018 at 14:38
  • @max, I don't understand why this is a dup. This question concerns a string; the referenced earlier question concerns an array of strings. Commented Jan 19, 2018 at 20:40
  • John, do you mean you want the desired output to be ["abc", "def", "mno"]? (abc;def;mno is not a Ruby object, which may account for the downvote). If so, you should edit. Commented Jan 19, 2018 at 20:45

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

for pure ruby can use arr = JSON.parse(str).reject(&:blank?)
0

Use this code:

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

Comments

0

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"

1 Comment

but its a string not an array('["", "abc", "", "def", "", "mno", "", "", "", "", ""]'), how can i convert this string into an array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.