Ren Ren - 1 month ago 11x
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 %>
<%= image_tag %>
<%= image_tag[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
statements to make the rendering of the second thumbnail conditional, but they don't work:

<% if %>
<% if %>
<% if[1]? %>
<% if[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


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

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

Maybe you can use this:

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