Merge arrays if not nil and not empty

2020-07-17 14:56发布

问题:

There are some arrays in Ruby (is this case there 4 array)

array1 = [{key="label1.1", value="label1.2"}, {key="label1.2", value="label1.2"}]
array2 = [{key="label2.1", value="label2.2"}]

array3 = []
array4 = nil
result_array = array1 | array2 | array3 | array4 

Each of arrays has the same structure as others: it's hash values. How many elements in it, if it's nil or empty - it's not known.

So I need result_array to look:

[{key="label1.1", value="label1.2"}, {key="label1.2", value="label1.2"}, {key="label2.1", value="label2.2"}]

However that code is going to cause an exception because array4 is equal to nil.

Is there any, Ruby, way to check if an array is not nil and not empty and if so, then merge it to result_array?

回答1:

[array1, array2, array3, array4].compact.reduce([], :|)


回答2:

Kernel defines a method called Array which will leave the arrays alone, but convert the nil into an empty array.

array1 = [{:key => "label1.1", :value => "label1.2"}, {:key =>"label1.2", :value => "label1.2"}]
array2 = [{:key => "label2.1", :value => "label2.2"}]

array3 = []
array4 = nil
result_array = Array(array1) | Array(array2) | Array(array3) | Array(array4)
result_array # => [{:key=>"label1.1", :value=>"label1.2"}, {:key=>"label1.2", :value=>"label1.2"}, {:key=>"label2.1", :value=>"label2.2"}]