For the first array x?
I guess this has a pretty simple answer
<% for user in @users %>
<li>
<%= link_to user.username, user %>
</li>
<% end %>
Taking my simple example above, how would I apply the class to mine <li>
on the first three instances returned?
Second, how could I just have that the second two elements have a different class from the first? how in1..2
source to share
Or you can count manually (which is pretty ugly):
<% i = 0 %>
<% for user in @users %>
<li class=<%= (i < 3 ? "foo" : "bar") %>>
<%= link_to user.username, user %>
</li>
<% i = i.next %>
<% end %>
or use each_with_index
<% @users.each_with_index do |user, i| %>
<li class=<%= (i < 3 ? "foo" : "bar") %>>
<%= link_to user.username, user %>
</li>
<% end %>
Once you get to more complicated things than i < 3
(for example, the problem with 1..2), you should think about helper_method
(in helpers
), for example class_by_position(pos)
, so that you can write
<li class=<%= class_by_position(i) %>>
source to share
Your question is a little vague. I can't tell if you want to stop processing the array after the first x or not.
If you just want to stop after the first x elements, or are just looking for the 2nd and 3rd items, the solution is to use a slice.
Example: only the first 3:
@user[0,3].each do |user|
... # only executed for user = @user[0],user = @user[1] and user = @user[3]
end
Example: only the second and third:
@user[1,2].each do |user|
... #only only executed for user = @user[1] and user = @user[3]
end
And here is a more specific answer to your question, using these new concepts and content_tag to solve the list item class programmatically. If you're going to be doing this a lot, this is a great candidate for the function.
<% first = true %>
<% @user[0,2].each do |user| %>
<% content_tag :li,
:class => first ? "class-for-first-item" : "class-for-2nd-&-3rd" do %>
<%= link_to user.username, user %>
<% end %>
<% first = false %>
<% end %>
<!-- Now to do the rest of them:-->
<% @user[3,-1].each do |user| %>
<% content_tag :li, :class => "class-for-rest" do %>
<%= link_to user.username, user %>
<% end %>
<% end %>
source to share