Array.shift问题

| 从我的控制器传递两个实例变量
@events = Event.all
@images = Images.all
。在视图中,我从遍历
@events.each do |event|
开始,并且在此块中是行
img = @images.shift
,但是当我尝试访问
img
之类的任何方法as4ѭ时,我得到
img
nil
的错误,但是我已经检查并确定
@images
已正确填充。如果仅输出
img.class
,我会收到正确的类
Image
,但无法访问它的任何方法。 我在做什么错?为什么从阵列中提取实例的这种方式不正确? 我知道还有其他解决方法,但是这个特定的问题使我感到困惑,我真的很想知道为什么这行不通。谢谢。
#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
    
已邀请:
当事件多于图像时,可能会发生此问题。因为每次迭代通过@events数组,然后@images都会移位并从数组中获取下一个元素。因此,当您在@events中有4个元素,而在@images中只有3个元素时,则在第4次迭代时,从@images中获取了第4个元素,这是
nil
    
two13ѭ的返回值变为ѭ7two的情况有两种。 数组的最左边元素是
nil
。 数组为空(= 16)。 可能是任何一种情况。     

要回复问题请先登录注册