本文介绍了如果不为 nil 且不为空,则合并数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

所以我需要 result_array 来查看:

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

然而,该代码将导致异常,因为 array4 等于 nil.

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

Ruby 有没有办法检查数组是否为 nil 且不为空,如果是,则将其合并到 result_array?

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?

推荐答案

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

这篇关于如果不为 nil 且不为空,则合并数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:47