Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 674
Ren Avatar asked Sep 06 '16 01:09

Ren


People also ask

What is an array in Ruby?

In Ruby, an array is a common data type. It contains elements of various data types, including number, string, boolean, and even another array. We may need to check if a value exists in a given array in some circumstances.

How to check if an element exists in an array?

The array contains a collection of elements, Sometimes we want to check if a given element exists in an array, resulting in a boolean values checks against conditional statements such as if-else. There are multiple ways we can check key element exists in an array. include? method checks element exists in an array, return true or false.

What is the use of find_Index in Ruby?

Ruby | Array class find_index () operation Array#find_index () : find_index () is a Array class method which returns the index of the first array. If a block is given instead of an argument, returns the index of the first object for which the block returns true.

What is the best way to search an array in Ruby?

Or if you're using Ruby 2.0, you can take advantage of bsearch. A binary search assumes the array is sorted (or ordered in some form) which can be costly for large arrays, often negating the advantage. A binary search also requires all pairs of elements to be comparable with <=>, which is not always the case.


Video Answer


1 Answers

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? %>
like image 152
Wenceslao Negrete Avatar answered Sep 21 '22 22:09

Wenceslao Negrete