Limit each do loop
45,112
Solution 1
<% @feed.sort_by{|t| - t.created_at.to_i}.first(10).each do |feed| %>
However, it's probably best to push this down into the model like this
<% @feed.recent(10).each do |feed| %>
And, in fact, if @feed
comes out of a database, I'd push it down even further: it doesn't make sense to load a ton of unsorted feed entries out of the DB, then sort them and then throw most of them away. Better let the DB do the sorting and filtering.
See @Peer Allan's answer for how to do it in ActiveRecord
. In ARel
(IOW: Rails 3) it would probably be even simpler, something like
Feed.all.order('created_at DESC').take(10)
Solution 2
[1,2,3,4,5].first(3)
=> [1,2,3]
Solution 3
I'd do it like this:
<% @array.limit(10).each do |a| %>
Solution 4
I agree with the others (Jörg in particular); but if you still want to know how to limit the loop itself, break
can be useful.
@array.each_with_index do |feed, i|
break if i == 10;
# ...
Solution 5
The following code will return 10 recent records.
@feed = @feed.sort! { |a,b| b.created_at <=> a.created_at }.take(10)
Related videos on Youtube
Comments
-
Karl Entwistle almost 2 years
If I have the following,
<% @feed.sort_by{|t| - t.created_at.to_i}.each do |feed| %> <% end %>
How can limit it to only show the 10 most recent results
-
Ed S. almost 14 yearsWhy don't you just sort first and then slice the array to get the first 10?
-
-
Victor over 12 yearsIf I wanna use
@feed
twice: one to show 10, another to show all, is it better for me to limit it in view withrecent(10)
, then the next just normal for loop for@feed
. -
Aleksander Pohl about 12 yearsThere are much better methods of limiting the number of displayed elements, than breaking the loop:
first
and[]
operator work very well in such a scenario. -
Amadan about 12 yearsI don't know about "better", but other answers are certainly nicer, which I specifically point out. "Better" is very situational; I might point out that the methods you propose make a new array, while mine doesn't. The point is, since the other answers already focused on limiting the collection itself, I answered just the literal question, adding another option: presupposing the loop over the whole collection, how to only run in 10 times max. It's not a solution I'd choose unless I was pressed for time, as it does make the code uglier.
-
Aleksander Pohl about 12 yearsYes it's matter of style mostly. But if there is a direct concept expressing the intent of a programmer (like
first
,[]
andorder(...).take(10)
especially) I personally find it more appealing to use it. -
mattd about 12 yearsAwesome. This allows you to limit after doing the sort. In my case, I'm sorting on the highest number of polymorphic associations. I can't write a query for it (don't know how!). This works nicely.