How do I remove blank elements from an array?

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

提交回复
热议问题