开发者

How can I tell the index of an array of objects in Ruby on Rails 3?

I have an array of todos [Todo1, Todo2, Todo3]

Each object has an attribute, :done_date

I need to find the first instance of the object where :done_date => null

THEN I need to know what index it is todos[N] so I can find the object before todos[N-开发者_如何学C1]

How can I do that?


You could try going about it in a slightly different way. Making use of Ruby's Enumerable#take_while:

# assuming 'todos' holds your todo objects
todos.take_while { |todo| todo.done_date != nil }.last

This will get all todo objects from todos until it sees a nil done_date, and then grab the last one. You'll have the last todo item before the first nil done_date.

So, if you have

todos = [todo1, todo2, todo3, todo4_with_null_done_date]

the code example above will return todo3.

That said, if you're really looking for something that makes use of the array's indicies, you could try something like this as well:

first_nil_index = todos.find_index { |todo| todo.done_date.nil? }
todos[first_nil_index - 1]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜