How do I remove blank elements from an array?

前端 未结 20 665
佛祖请我去吃肉
佛祖请我去吃肉 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:39
    1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)
    
    => ["A", "B", "C"]
    
    0 讨论(0)
  • 2020-11-30 17:39

    Here is a solution if you have mixed types in your array:

    [nil,"some string here","",4,3,2]
    

    Solution:

    [nil,"some string here","",4,3,2].compact.reject{|r| r.empty? if r.class == String}
    

    Output:

    => ["some string here", 4, 3, 2]
    
    0 讨论(0)
提交回复
热议问题