>我有这样的嵌套数组:
['foo', [nil], 'baz', ['bar'], nil, ['zoo']]
优雅地删除nil
但保留空数组? 我希望看到:
['foo', [], 'baz', ['bar'], ['zoo']]
有什么帮助大师吗?
*一次迭代
尝试代码:
array = ['foo', [nil], 'baz', ['bar'], nil, ['zoo']]
array.map! {|v| v.is_a?( Array ) && v.compact || v }.compact
# => ["foo", [], "baz", ["bar"], ["zoo"]]
或更灵活:
array.map! {|v| v.respond_to?( :compact ) && v.compact || v }.compact
# => ["foo", [], "baz", ["bar"], ["zoo"]]
或带陷阱:
array.map! {|v| v.compact rescue v }.compact
# => ["foo", [], "baz", ["bar"], ["zoo"]]
我会做如下:
a = ['foo', [nil], 'baz', ['bar'], nil, ['zoo']]
a.map { |e| e.is_a?(Array) ? e.compact : e }.compact
# => ['foo', [], 'baz', ['bar'], ['zoo']]
更新:
a.map { |e| e.instance_of?(Array) ? e.compact : e }.compact
更干净的instance_of?
,如果对象是该确切类的实例,而不是子类,则返回true
。
下面是一个适用于更深嵌套的递归版本:
a = ['foo', [nil, [nil, nil, [nil, 1, 2]]], 'baz', ['bar'], nil, ['zoo']]
def recursive_conpact(arr)
arr.is_a?(Array) ? arr.compact.map{|x|recursive_conpact(x)} : arr
end
p recursive_conpact(a) #=> ["foo", [[[1, 2]]], "baz", ["bar"], ["zoo"]]