Search code examples
ruby-on-railsdata-retrieval

get first 3 occurrence of an array


In my rails app I have below code to print some data from database.

<% @di.each do |d| %>
  <% if d["visibility_team"] == 'for_all' %>
   //my code goes here
  <% end %>
<% end %>

I just want to print first 3 occurrence which fulfill the d["visibility_team"] == 'for_all' condition.

How can I do this?


Solution

  • If you can't get @di as 3 records from DB, how about keeping counter how many ds were printed?

    Something like this (feel free to style it the way you want)

    <% counter = 0 %>
    <% @di.each do |d| %>
      <% if d["visibility_team"] == 'for_all' %>
         <% counter += 1 %>
         <% break if counter == 3 %>
       //your code goes here
      <% end %>
    <% end %>
    

    However it's usually a bad taste to have so much logic in views.