Reputation: 2153
I have this array of arrays:
["[]", "[\"https://somewebsite1.com\"]", "[\"https://somewebsite2.com\"]", "[]", "[]", "[]", "---\n- https://somewebsite3.com\n", "--- []\n", "---\n- https://somewebsite4.com\n", "--- []\n", "--- []\n", "---\n- https://somewebsite.com\n", "---\n- https://somewebsite5.com\n", nil, nil, nil, nil, nil]
How can I:
1- remove all the empty, nil element
2- have an array of string:
["https://somewebsite1.com", "https://somewebsite2.com", "https://somewebsite3.com", "https://somewebsite4.com", "https://somewebsite.com", "https://somewebsite5.com"]
array.select &:present?
remove nil
then array.delete_if {|i| i == '[]'}
remove []
so I am left with :
["[\"https://somewebsite1.com\"]", "[\"https://somewebsite2.com\"]", "---\n- https://somewebsite3.com\n", "--- []\n", "---\n- https://somewebsite4.com\n", "--- []\n", "--- []\n", "---\n- https://somewebsite.com\n", "---\n- https://somewebsite5.com\n"]
Upvotes: 0
Views: 4894
Reputation: 1429
To just remove nil elements, you can use the compact
method on an array.
To remove both nil and empty strings, you can use the select
method:
my_array.select! { |element| element&.size.to_i > 0 }
To process the remaining strings, you'll need to iterate over each string and figure out whether it needs YAML parsing or not. The method you'll use to collect the results of that iteration is map
:
my_array.map! { |element| clever_string_parsing_on(element) }
Upvotes: 1
Reputation: 4386
First of all, it is a simple array of strings.
You can remove nil elements using array.compact
or array.reject(&:nil?)
And to remove empty yaml entries you can use deserialization
array.compact
.reject { |i| YAML.parse(i).children.first.children.empty? }
.map { |i| i.gsub('["', '').gsub('"]', '').gsub("---\n- ", '').strip }
So the output would be you stated.
Update:
Another approach, without string manipulation
res = a.compact
deserialized = res.map { |i| YAML.parse(i) }
res = deserialized.reject { |i| i.children.first.children.empty? }
res.map { |i| i.children.first.children.first.value }
Upvotes: 3