Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to remove nil elements from an array in Rails

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 9.23k
    Comment on it


    We can remove nil elements from an array in number of ways. Here i am demonstrating the frequently used methods for removing nil elements from an array.

    1> using present method with reject

    1. >> [ "a", nil, "b", nil, "c", nil ].reject {|e| !e.present?}
    2. => ["a", "b", "c"]

    2> using compact method

    1. >> [ "a", nil, "b", nil, "c", nil ].compact
    2. => ["a", "b", "c"]

    3> using blank method with reject

    1. >> [ "a", nil, "b", nil, "c", nil ].reject {|e| e.blank?}
    2. => ["a", "b", "c"]

    4> using present method with select

    1. >> [ "a", nil, "b", nil, "c", nil ].select {|e| e.present?}
    2. => ["a", "b", "c"]

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: