Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR / Ruby delete nil elements from nested array

To split an array into two equal pieces I would do this,

>> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> a.in_groups_of( (a.size/2.0).ceil ) if a.size > 0
=> [[1, 2, 3], [4, 5, nil]]

Now I've got a nested array that contains nil elements if the size of the array is odd. How can I remove the nil elements from the nested arrays? I want to do something like,

a.compact

But unfortunately that doesn't work, ruby only removes nil elements on the first level and not recursively. Does ruby provide any nice solutions for this problem?

like image 850
Patrick Oscity Avatar asked Nov 25 '09 23:11

Patrick Oscity


People also ask

How do you remove nil from an array?

Syntax: Array. compact() Parameter: Array to remove the 'nil' value from. Return: removes all the nil values from the array.

How do you remove one element from an array in Ruby?

Ruby | Array delete() operation Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array. delete() Parameter: obj - specific element to delete Return: last deleted values from the array.


1 Answers

With Ruby 1.8.7 and later you can do the following:

a.each &:compact!
=> [[1, 2, 3], [4, 5]]

With Ruby 1.8.6, you have do do this the long way:

a.each {|s| s.compact!}

Both of these will modify the contents of a. If you want to return a new array and leave the original alone, you can use collect instead of each:

# 1.8.7+:
a.collect &:compact

# 1.8.6:
a.collect {|s| s.compact}
like image 77
Phil Ross Avatar answered Sep 29 '22 15:09

Phil Ross