Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby iterate over a variable unless it is nil

I would like a clean way in .html.erb to loop through a variable ONLY if the variable is not nil.

I would like the following to execute but not if @family is nil.

<% @family.children.each.with_index(1) do |family_member, index| %>
    // HTML HERE
<% end %>

I am trying to avoid doing something like this

<% if @family %>
   <% @family.children.each.with_index(1) do |family_member, index| %>
       // HTML HERE
   <% end %>
<% end %>

And especially trying to avoid needing

<% if @family && @family.children %>
      <% @family.children.each.with_index(1) do |family_member, index| %>
          // HTML HERE
      <% end %>
<% end %>

Is there a better way to do this?

like image 407
MicFin Avatar asked Aug 18 '15 16:08

MicFin


1 Answers

This solution can be misleading but Ruby's syntax allows you to do so:

<% @family.children.each.with_index(1) do |family_member, index| %>
    // HTML HERE
<% end unless @family.blank? %>
#      ^^^^^^^^^^^^^^^^^^^^^

I only use this solution for simple statements like testing the presence of an object (like in your case). I do not recommend this solution for a more complex logic because a third party would not know that the condition is at the end of the block.


Another one:

<% (@family.try(:children) || []).each.with_index(1) do |family_member, index| %>

# mu-is-too-short's (brilliant) suggestion:
<% @family.try(:children).to_a.each.with_index(1) do |family_member, index| %>

If @family is nil, the try(:children) won't raise an error but will return nil, then nil || [] returns the empty array which "you can loop on it" (loop on it zero times actually).

like image 129
MrYoshiji Avatar answered Oct 03 '22 01:10

MrYoshiji