Tuesday, July 7, 2009

minimum method for the Array class

Hi,

I used the wrong method in class last night in the solution for the minimum method. I used collect the collect method on the array to get rid of the nil elements when I should have used select.

Here's the correct way to do it:

class Array
   def minimum
     self.select { |e| e != nil }.sort.first
   end
end

puts [1, 2, -10, nil, 52.7].minimum # -10

You can also get rid of the nil elements using the compact method:

class Array
   def minimum
     self.compact.sort.first
   end
end

puts [1, 2, -10, nil, 52.7].minimum # -10

No comments:

Post a Comment