Nil.each error

When I run the following code in the console I get the following error:

s_date = Date.new(2007,6,3)
e_date = Date.new(2007,7,3)

due_dates = DueDate.find(:all, :conditions => [‘stamp >= ? and stamp <=
?’,s_date.to_s(:db),e_date.to_s(:db)], :order => ‘stamp desc’)

sales_orders = []

due_dates.each { |dd| sales_orders << dd.so_number }

@histories = History.find_by_sales_orders(sales_orders)

@histories.compact!.each { |history|
@total += 1
if history.sales_order_has_ec?
if history.ec_date >
DueDate.find_by_sales_order(history.so_number).stamp
@late += 1
elsif history.ec_date <
DueDate.find_by_sales_order(history.so_number).stamp
@early += 1
else
@on_time += 1
end
else
@incomplete += 1
end
}

NoMethodError: You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+
from (irb):20
from (irb):19:in `each’
from (irb):19

What am I doing wrong here? I checked all the arrays used here, and
they all have values; none of them are empty.

Thanks!

due_dates.each { |dd| sales_orders << dd.so_number }

@histories = History.find_by_sales_orders(sales_orders)

@histories.compact!.each { |history|

Get rid of the ‘!’.

Get rid of the ‘!’.

Ok, that worked! But, why did it work? I don’t understand why the !
makes a difference…

Hi –

On Tue, 3 Jul 2007, Jason F. wrote:

Get rid of the ‘!’.

Ok, that worked! But, why did it work? I don’t understand why the !
makes a difference…

Array#compact! is one of a number of methods that change their
receiver but return nil if there’s no change. So:

[1,2,3].compact! # nil

Remember that the ! means “dangerous” – expect the unexpected :slight_smile:

David

Makes sense. I know I’ve read that before, but obviously forgot it…

Thanks!