Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.2ruby-on-rails-3.1

skip array results if condition repeated


The articles.facets['date']['terms'] have this array:

[{"term"=>13, "count"=>4}, {"term"=>12, "count"=>1}]

I would like print only once this text "More than 10 years" if there is more than one element of the array that meets the requirement of being over 10 years old

<% articles.facets['yearsexperience']['terms'].each do |facet| %>
  <% if facet['term'] > 10 %>
    "More than 10 years"
  <% end %>
<% end %>

I'm getting now 2 times the same text:

"More than 10 years" 
"More than 10 years"

Solution

  • Use .any?. It accepts a block which it invokes for each element in the enumerable, and returns true if the block returns true for any elements in the array:

    <% if articles.facets["yearsexperience"]["terms"].any? { |t| t['term'] > 10 } %>
      More than 10 years
    <% end %>