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
>> [ "a", nil, "b", nil, "c", nil ].reject {|e| !e.present?}
=> ["a", "b", "c"]
2> using compact method
>> [ "a", nil, "b", nil, "c", nil ].compact
=> ["a", "b", "c"]
3> using blank method with reject
>> [ "a", nil, "b", nil, "c", nil ].reject {|e| e.blank?}
=> ["a", "b", "c"]
4> using present method with select
>> [ "a", nil, "b", nil, "c", nil ].select {|e| e.present?}
=> ["a", "b", "c"]
0 Comment(s)