Forum: Ruby on Rails nil.each error

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jason F. (Guest)
on 2007-07-03 22:52
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!
Philip H. (Guest)
on 2007-07-03 22:58
(Received via mailing list)
> 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 '!'.
Jason F. (Guest)
on 2007-07-03 23:01
> Get rid of the '!'.


Ok, that worked!  But, why did it work?  I don't understand why the !
makes a difference....
unknown (Guest)
on 2007-07-03 23:27
(Received via mailing list)
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 :-)


David

--
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)
Jason F. (Guest)
on 2007-07-03 23:29
Makes sense.  I know I've read that before, but obviously forgot it....

Thanks!
This topic is locked and can not be replied to.