How do I remove blank elements from an array?

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

    There are already a lot of answers but here is another approach if you're in the Rails world:

     cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].select &:present?
    
    0 讨论(0)
  • 2020-11-30 17:31

    There are many ways to do this, one is reject

    noEmptyCities = cities.reject { |c| c.empty? }
    

    You can also use reject!, which will modify cities in place. It will either return cities as its return value if it rejected something, or nil if no rejections are made. That can be a gotcha if you're not careful (thanks to ninja08 for pointing this out in the comments).

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

    Plain Ruby:

    values = [1,2,3, " ", "", "", nil] - ["", " ", nil]
    puts values # [1,2,3]
    
    0 讨论(0)
  • 2020-11-30 17:35
     cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.empty? } 
    
    0 讨论(0)
  • 2020-11-30 17:36
    cities.reject! { |c| c.blank? }
    

    The reason you want to use blank? over empty? is that blank recognizes nil, empty strings, and white space. For example:

    cities = ["Kathmandu", "Pokhara", " ", nil, "", "Dharan", "Butwal"].reject { |c| c.blank? }
    

    would still return:

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

    And calling empty? on " " will return false, which you probably want to be true.

    Note: blank? is only accessible through Rails, Ruby only supports empty?.

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

    Most Explicit

    cities.delete_if(&:blank?)
    

    This will remove both nil values and empty string ("") values.

    For example:

    cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal", nil]
    
    cities.delete_if(&:blank?)
    # => ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
    
    0 讨论(0)
提交回复
热议问题