b_d
b_d

Reputation: 787

Problem with Array.shift

From my controller I am passing two instance variables @events = Event.all and @images = Images.all. In the view I begin by iterating through @events.each do |event| and within this block is the line img = @images.shift yet when I try to access any method of img such as img.filename I get an error that img is nil but I have checked and am certain that @images is populated correctly. If I simply output img.class I receive the correct class, Image, but cannot access any of it's methods.

What am I doing wrong or why is this way of pulling instances from an array incorrect?

I know there are other ways of going about this but this specific problem confounds me and I would really like to understand why this doesn't work. Thanks.

#Structure of the model is
Image
-filename :string
-date     :datetime
-caption  :text
-source   :string

#Controller
def index
  @events = Event.all
  @images = Image.all
end

#index.html.erb
<% @events.each do |event| %>
  ... code that works ...

  <% if count==1%>
    <% img = @images.shift %>
    <div><%= img.filename %></div>
  <% end %>

<% end %>

#For testing purposes I changed
<% img = @images.shift %>
<div><%= img.class %></div>

#output is Image

Upvotes: 0

Views: 751

Answers (2)

sawa
sawa

Reputation: 168101

There are two cases when the return value of Array#shift becomes nil.

  1. The leftmost element of the array is nil.
  2. The array is empty (= []).

It is probably either of the cases.

Upvotes: 1

Ireneusz Skrobis
Ireneusz Skrobis

Reputation: 1533

The problem might occur when there is more events then images. Because every time an iteration goes through @events array then the @images are shifted and is taken the next element from the array. So when you have for example 4 elements in @events and only 3 in @images then at 4th iteration there is taken 4th element from @images and this is nil

Upvotes: 2

Related Questions