cmaxvv
September 4, 2007, 11:44am
1
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…
cmaxvv
September 4, 2007, 4:48pm
2
There must be a better way than this, but it’ll work
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
cmaxvv
September 4, 2007, 5:06pm
3
Ivan Trajkovic wrote:
There must be a better way than this, but it’ll work
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
cmaxvv
September 25, 2007, 11:10pm
4
Here is my 2cents worth, but I would love to learn a better way.