How do I remove blank elements from an array?

前端 未结 20 667
佛祖请我去吃肉
佛祖请我去吃肉 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:20

    Shortest way cities.select(&:present?)

    0 讨论(0)
  • 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"]
    
    0 讨论(0)
  • 2020-11-30 17:22

    Try this:

    puts ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - [""]
    
    0 讨论(0)
  • 2020-11-30 17:27

    Use reject:

    >> cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].reject{ |e| e.empty? }
    => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
    
    0 讨论(0)
  • 2020-11-30 17:28

    Update with a strict with join & split

    cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"]
    cities.join(' ').split
    

    Result will be:

    ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
    

    Note that: this doesn't work with a city with spaces

    0 讨论(0)
  • 2020-11-30 17:29

    When I want to tidy up an array like this I use:

    ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"] - ["", nil]
    

    This will remove all blank or nil elements.

    0 讨论(0)
提交回复
热议问题