6

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

1
  • 1
    Wenceslao's answer is good. The key to this is that in Ruby, Arrays can be accessed beyond their conceptual size safely. For example, for an array a = [1] you can check an index and if nothing is there, it will return nil. So array.photos[1].nil? is the easiest way to decide if anything is there. Commented Sep 6, 2016 at 1:41

2 Answers 2

9

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) %>

Or:

<%= image_tag array.photos[1].image.url(:thumb) unless array.photos[1].nil? %>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, the !array.photos[1].nil? approach was what i was looking for
however i used different syntax with the if clause at the end of the line
1

Here, why not

(0...array.photos.size).each do |photo|
    ......
end

array.photos.each do |photo|
    ......
end

1 Comment

because he's trying to access a specific index that he doesn't know will be occupied or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.