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
An easy way to go about this would be to put the user-input prompt inside of a while loop, and only break out once you've verified that the grade is valid: Scanner scanner = new Scanner(System.in); int score; while (true) { System. out. print("Please enter score " + (g + 1) + ": "); score = scanner.
zip(range(limit), items) Using Python 3, zip and range return iterables, which pipeline the data instead of materializing the data in lists for intermediate steps. To get the same behavior in Python 2, just substitute xrange for range and itertools. izip for zip .
In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.
In Ruby, for loops are used to loop over a collection of elements.
<% @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)
Array#first(n)
[1,2,3,4,5].first(3) => [1,2,3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With