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

John
  • 1,204
  • 3
  • 20
  • 52
  • You can simple do it in one line using JSON.parse(a).reject(&:empty?).join(';') – sam Jan 19 '18 at 11:51
  • Just for your example `string.scan(/\w+/) #=> ["abc", "def", "mno"]` but not really a general solution. – Sagar Pandya Jan 19 '18 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. – Cary Swoveland Jan 19 '18 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. – Cary Swoveland Jan 19 '18 at 20:45

2 Answers2

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

Mikhail Katrin
  • 2,097
  • 1
  • 10
  • 17
0

Use this code:

str = YAML.load('["", "abc", "", "def", "", "mno", "", "", "", "", ""]')
str.select{|a| a if a != ""}.join(";")
Uday kumar das
  • 1,597
  • 14
  • 33