Merge arrays if not nil and not empty

时光毁灭记忆、已成空白 提交于 2020-01-01 13:38:05

问题


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


来源:https://stackoverflow.com/questions/12228709/merge-arrays-if-not-nil-and-not-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!