Finding the position on an item in a collection

This feels like it should be easy but i can’t work it out: if i have a
collection of stories, ordered by (for example) date, then how do i find
out the position of the story with id = (eg) 23 in the collection?

I guess this is a ruby question rather than a rails-specific question,
but maybe there’s a rails way…

There must be a better way than this, but it’ll work :wink:

You can try iterating trough the collection with a counter, and setting
the position value on the hit. Something like this:

counter = 0
position = 0

for story in @stories
if story.id == 23
position = counter
end
counter = counter + 1
end

Ivan Trajkovic wrote:

There must be a better way than this, but it’ll work :wink:

You can try iterating trough the collection with a counter, and setting
the position value on the hit. Something like this:

counter = 0
position = 0

for story in @stories
if story.id == 23
position = counter
end
counter = counter + 1
end

Thanks ivan, i ended up doing something similar but a little bit nicer
after a suggestion elsewhere:

@stories.each_with_index do |item, index|
if item.id == 23
position = index
break
end
end

thanks for helping though :slight_smile:

Here is my 2cents worth, but I would love to learn a better way.