How do I remove blank elements from an array?

前端 未结 20 669
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 16:43

I have the following array

cities = [\"Kathmandu\", \"Pokhara\", \"\", \"Dharan\", \"Butwal\"]

I want to remove blank elements from the ar

20条回答
  •  情深已故
    2020-11-30 17:21

    compact_blank (Rails 6.1+)

    If you are using Rails (or a standalone ActiveSupport), starting from version 6.1, there is a compact_blank method which removes blank values from arrays.

    It uses Object#blank? under the hood for determining if an item is blank.

    ["Kathmandu", "Pokhara", "", "Dharan", nil, "Butwal"].compact_blank
    # => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
    
    [1, "", nil, 2, " ", [], {}, false, true].compact_blank
    # => [1, 2, true]
    

    Here is a link to the docs and a link to the relative PR.

    A destructive variant is also available. See Array#compact_blank!.


    If you need to remove only nil values,

    please, consider using Ruby build-in Array#compact and Array#compact! methods.

    ["a", nil, "b", nil, "c", nil].compact
    # => ["a", "b", "c"]
    

提交回复
热议问题