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
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.
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.
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.
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.
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? %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With