gpt4 book ai didi

ruby - 嵌套数组删除 nil

转载 作者:太空宇宙 更新时间:2023-11-03 17:10:56 26 4
gpt4 key购买 nike

我有这样的嵌套数组:

['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"]]

关于ruby - 嵌套数组删除 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21253157/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com