Forum: Ruby on Rails creating empty array of items - should be a quick simple one

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.
Debcfd8f3f533800e2711c704825f9c0?d=identicon&s=25 Scott Kulik (kuliksco)
on 2008-11-07 05:01
here is some of the code:

    @items_all = Item.find(:all)

    for item in @items_all do
      if not FileTest.exist?(item.image_name)
        @items_missing_images += item
      end
    end

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.+

at @items_missing_images += item

so...how can i declare an empty array of Items?

i tried declaring @items_missing_images = []

but item is not of type array so this won't work.
F47bebf5f4b10b709a59310027c8f977?d=identicon&s=25 Robert Zotter (Guest)
on 2008-11-07 05:14
(Received via mailing list)
Scott,

You need to declare the empty array first.
@items_missing_images = []

But do not use the '@items_missing_images += item '
Use @items_missing_images.push(item)
or    @items_missing_images << item

The += only works if you are adding an array to an array.

http://ruby-doc.org/core/classes/Array.html#M002232

Cheers

--
Robert Zotter
Zapient, LLC
Ruby on Rails Development and Consulting

http://www.zapient.com
http://www.fromjavatoruby.com

On Nov 6, 8:01 pm, Scott Kulik <rails-mailing-l...@andreas-s.net>
F47bebf5f4b10b709a59310027c8f977?d=identicon&s=25 Robert Zotter (Guest)
on 2008-11-07 05:19
(Received via mailing list)
I probably should mention the best way to do what you are trying to
accomplish would be:

@items_missing_images = @items_all.reject { |item| FileTest.exist?
(item.image_name) }

--
Robert Zotter
Zapient, LLC
Ruby on Rails Development and Consulting

http://www.zapient.com
http://www.fromjavatoruby.com
Debcfd8f3f533800e2711c704825f9c0?d=identicon&s=25 Scott Kulik (kuliksco)
on 2008-11-07 05:27
thanks for both replies!  that's exactly what i was looking for.
Afc4dcff69407649ec9c541a77b91e0a?d=identicon&s=25 Chas Lemley (Guest)
on 2008-11-07 09:28
(Received via mailing list)
I'm new to this but could you do this:

above this put

@items_missing_images = Array.new

and then in your if statement do this

@items_missing_images << item

Chas

On Thu, Nov 6, 2008 at 11:01 PM, Scott Kulik <
This topic is locked and can not be replied to.