Ren*_*Ren 4 ruby arrays ruby-on-rails
是否有Ruby(最好)或Rails方法来检查数组的第二个索引是否存在?
在我的Rails(4.2.6)应用程序中,我在视图中有以下代码,显示了一组照片的前两个缩略图:
<% if array.photos.any? %>
<%= image_tag array.photos.first.image.url(:thumb) %>
<%= image_tag array.photos[1].image.url(:thumb) %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
但是,如果数组中没有第二项,则会出现错误
我已经尝试了以下if语句来使第二个缩略图的呈现有条件,但它们不起作用:
<% if array.photos.include?(1) %>
<% if array.photos.second? %>
<% if array.photos[1]? %>
<% if array.photos[1].any? %>
Run Code Online (Sandbox Code Playgroud)
我认为另一种获得我想要的方法是简单地检查数组的长度
我仍然想知道Ruby(或Rails)是否有方法或方法来检查数组中是否存在特定索引.提前致谢
编辑:澄清我只想显示数组中的前两个缩略图,如果有的话
小智 7
您可以使用.each,但是如果您想使用此方法.而不是这个:
<%= image_tag array.photos[1].image.url(:thumb) %>
Run Code Online (Sandbox Code Playgroud)
也许你可以用这个:
<%= if(!array.photos[1].nil?) image_tag array.photos[1].image.url(:thumb) %>
Run Code Online (Sandbox Code Playgroud)