Fellow Stranger Fellow Stranger - 2 years ago 132
Ruby Question

Reiterate over collection

I have an unknown number of categories.

I want to pick one post from each category, and when there are no more categories I want to start from the beginning until I've reached a fixed number posts.

This is what I have, how could I rerun this iteration until I have my desired amount of posts?

desired_amount = 40
categories.each_with_index do |category, index|
post = category.posts.order(position: :asc)[index]
# do something with the post
return if desired_amount == (index + 1)

Answer Source

Personally, I would much prefer something like this:

posts = categories.cycle.take(desired_amount).each_with_index.map do |cat,ind|
  cat.posts.order(position: :asc)[ind / categories.count]

That would give you the first post in each category, followed by the second post in each category, etc, until you had the number of posts you wanted. The one caveat is that if any category didn't have enough posts, your final array would have some empty spots in it (i.e. nils).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download