Ren Ren - 3 months ago 25
Ruby Question

How to check if an array index exists using Ruby and/or Rails

Is there a Ruby (preferably) or Rails way to check if the second index of an array exists?

In my Rails (4.2.6) app I have the following code in my view that shows the first two thumbnails for an array of photos:

<% if array.photos.any? %>
<%= image_tag array.photos.first.image.url(:thumb) %>
<%= image_tag array.photos[1].image.url(:thumb) %>
<% end %>


However if there is no second item in the array, then there is an error

I've tried the following
if
statements to make the rendering of the second thumbnail conditional, but they don't work:

<% if array.photos.include?(1) %>
<% if array.photos.second? %>
<% if array.photos[1]? %>
<% if array.photos[1].any? %>


I figured that another way to get what I want would be to simply check the length of the array

Still I was wondering if Ruby (or Rails) had a method or way to check if a specific index in an array exists or not. Thanks in advance

EDIT: To clarify I just want to show the first two thumbnails in the array, if any

Answer

You can use an .each, but if you want to follow this approach. Instead of this:

<%= image_tag array.photos[1].image.url(:thumb) %>

Maybe you can use this:

<%= if(!array.photos[1].nil?) image_tag array.photos[1].image.url(:thumb) %>