如果不是nil而不是空,则合并数组

时间:2021-02-02 15:58:05

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

Ruby中有一些数组(这种情况下有4个数组)

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:

所以我需要result_array来看:

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

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

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

但是,该代码将导致异常,因为array4等于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?

是否有任何Ruby方法来检查数组是否为空且不为空,如果是,则将其合并到result_array?

2 个解决方案

#1


10  

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

#2


3  

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

内核定义了一个名为Array的方法,该方法将使数组保持单独,但将nil转换为空数组。

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"}]

#1


10  

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

#2


3  

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

内核定义了一个名为Array的方法,该方法将使数组保持单独,但将nil转换为空数组。

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"}]