How do I remove blank elements from an array?

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

    In my project I use delete:

    cities.delete("")
    
    0 讨论(0)
  • 2020-11-30 17:14

    To remove nil values do:

     ['a', nil, 'b'].compact  ## o/p =>  ["a", "b"]
    

    To remove empty strings:

       ['a', 'b', ''].select{ |a| !a.empty? } ## o/p => ["a", "b"]
    

    To remove both nil and empty strings:

    ['a', nil, 'b', ''].select{ |a| a.present? }  ## o/p => ["a", "b"]
    
    0 讨论(0)
  • 2020-11-30 17:15

    Here is what works for me:

    [1, "", 2, "hello", nil].reject(&:blank?)
    

    output:

    [1, 2, "hello"]
    
    0 讨论(0)
  • 2020-11-30 17:19

    another method:

    > ["a","b","c","","","f","g"].keep_if{|some| some.present?}
    => ["a","b","c","f","g"]
    
    0 讨论(0)
  • 2020-11-30 17:20

    Here is one more approach to achieve this

    we can use presence with select

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

    You can Try this

     cities.reject!(&:empty?)
    
    0 讨论(0)
提交回复
热议问题