-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,273
  • 3
  • 27
  • 61
  • 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

3 Answers3

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,304
  • 1
  • 9
  • 17
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"
potashin
  • 44,205
  • 11
  • 83
  • 107
  • but its a string not an array('["", "abc", "", "def", "", "mno", "", "", "", "", ""]'), how can i convert this string into an array? – John Jan 19 '18 at 09:59
0

Use this code:

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