views:

457

answers:

4

in a previous question i asked how to split an array into two equal pieces in ruby on rails. this is how i did it:

>> 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?

A: 
a.each {|subarray| subarray.compact!}
a.compact!

Should work....

+1  A: 

Unless you want to permanently change a

a.map do |e|
  e.compact
end
Styggentorsken
+5  A: 

In Ruby 1.8.7 and 1.9 you can do the following:

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

In 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 and 1.9:
a.collect &:compact

# 1.8.6:
a.collect {|s| s.compact}
Phil Ross
EmFi
@EmFi Good point - I was forgetting 1.8.7. I'll edit my answer.
Phil Ross
+3  A: 

If you were to use the in_groups_of you can pass it false as the second argument and it will not fill in the "blanks" with nil, but truly nothing.

Ryan Bigg